Index: sm/trunk/config.guess
===================================================================
--- /issm/trunk/config.guess	(revision 16559)
+++ 	(revision )
@@ -1,1542 +1,0 @@
-#! /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: sm/trunk/config.sub
===================================================================
--- /issm/trunk/config.sub	(revision 16559)
+++ 	(revision )
@@ -1,1677 +1,0 @@
-#! /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/configs/config-linux64-pleiades-ampi-gcc.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-ampi-gcc.sh	(revision 16560)
+++ /issm/trunk/configs/config-linux64-pleiades-ampi-gcc.sh	(revision 16560)
@@ -0,0 +1,19 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-wrappers=no \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/mvapich2/1.6.sles11/gcc/include" \
+	--with-mpi-libflags="-L/nasa/mvapich2/1.6.sles11/gcc/lib -llmpe -lmpe -lmpich" \
+	--with-adolc-dir="$ISSM_DIR/externalpackages/adolc/install"\
+	--with-ampi-dir="$ISSM_DIR/externalpackages/adjoinablempi/install"\
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades-gcc"
Index: /issm/trunk/configs/config-linux64-pleiades-ampi.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-ampi.sh	(revision 16560)
+++ /issm/trunk/configs/config-linux64-pleiades-ampi.sh	(revision 16560)
@@ -0,0 +1,19 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-wrappers=no \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+	--with-mpi-libflags="-L/nasa/sgi/mpt/2.06rp16/ -lmpi -lmpi++" \
+	--with-adolc-dir="$ISSM_DIR/externalpackages/adolc/install"\
+	--with-ampi-dir="$ISSM_DIR/externalpackages/adjoinablempi/install"\
+	--with-mkl-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+	--with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-O3" \
+	--with-vendor="intel-pleiades"
Index: /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 16560)
+++ /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 16560)
@@ -0,0 +1,17 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/mvapich2/1.4.1/gcc.sles11/include"\
+	--with-mpi-libflags=" -L/nasa/mvapich2/1.4.1/gcc.sles11/lib -lmpichcxx -lmpich -lpthread -lrdmacm -libverbs -libumad -lrt" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades-gcc"
Index: /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 16560)
+++ /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 16560)
@@ -0,0 +1,18 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/mvapich2/1.6.sles11/gcc/include" \
+	--with-mpi-libflags="-L/nasa/mvapich2/1.6.sles11/gcc/lib -lmpich -lopa -lpthread -lrdmacm -libverbs -libumad -ldl -lrt" \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades-gcc"
Index: /issm/trunk/configs/config-linux64-skylla.sh
===================================================================
--- /issm/trunk/configs/config-linux64-skylla.sh	(revision 16560)
+++ /issm/trunk/configs/config-linux64-skylla.sh	(revision 16560)
@@ -0,0 +1,22 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir=$ISSM_DIR/externalpackages/matlab/install \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.2/ -lgfortran" \
+ --with-graphics-lib="/usr/lib64/libX11.so.6" \
+ --with-cxxoptflags="-g -O2" \
+ --with-numthreads=8
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 16559)
+++ /issm/trunk/configure.ac	(revision 16560)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.4],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([Ice Sheet System Model (ISSM)],[4.4],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
 AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
 AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 16559)
+++ /issm/trunk/etc/environment.sh	(revision 16560)
@@ -76,4 +76,6 @@
 	libpathappend "$MPI_DIR/lib"
 fi
+
+export MPI_INC_DIR="$MPI_DIR/include"
 
 PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
Index: /issm/trunk/externalpackages/adjoinablempi/install-pleaides.sh
===================================================================
--- /issm/trunk/externalpackages/adjoinablempi/install-pleaides.sh	(revision 16560)
+++ /issm/trunk/externalpackages/adjoinablempi/install-pleaides.sh	(revision 16560)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="/nasa/sgi/mpt/2.06rp16/" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/adolc/install-withampi-pleiades-gcc.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-withampi-pleiades-gcc.sh	(revision 16560)
+++ /issm/trunk/externalpackages/adolc/install-withampi-pleiades-gcc.sh	(revision 16560)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root="/nasa/mvapich2/1.6.sles11/gcc" \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/trunk/externalpackages/adolc/install-withampi-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-withampi-pleiades.sh	(revision 16560)
+++ /issm/trunk/externalpackages/adolc/install-withampi-pleiades.sh	(revision 16560)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root="/nasa/sgi/mpt/2.06rp16/" \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/trunk/externalpackages/freetype/install.sh
===================================================================
--- /issm/trunk/externalpackages/freetype/install.sh	(revision 16559)
+++ /issm/trunk/externalpackages/freetype/install.sh	(revision 16560)
@@ -5,16 +5,16 @@
 rm -rf src
 rm -rf install
-rm -rf freetype-2.4.9
+rm -rf freetype-2.5.0
 mkdir src install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/freetype-2.4.9.tar.gz' 'freetype-2.4.9.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/freetype-2.5.0.tar.gz' 'freetype-2.5.0.tar.gz'
 
 #Untar 
-tar -zxvf  freetype-2.4.9.tar.gz
+tar -zxvf  freetype-2.5.0.tar.gz
 
 #Move freetype into src directory
-mv freetype-2.4.9/* src
-rm -rf freetype-2.4.9
+mv freetype-2.5.0/* src
+rm -rf freetype-2.5.0
 
 #Configure freetype
Index: /issm/trunk/externalpackages/petsc/install-3.4-greenplanet.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-greenplanet.sh	(revision 16560)
+++ /issm/trunk/externalpackages/petsc/install-3.4-greenplanet.sh	(revision 16560)
@@ -0,0 +1,55 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-dir=/sopt/mpi/openmpi-1.5.4_psm/intel/ \
+ --with-blas-lapack-dir=/opt/intel/mkl/10.2.4.032/ \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l nodes=1:ppn=1
+#PBS -q c6145
+#PBS -l walltime=10
+
+cd $(echo $ISSM_DIR)/externalpackages/petsc/src/
+mpiexec -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 16559)
+++ /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 16560)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.2 src
+rm -rf install petsc-3.4.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.2.tar.gz
-mv petsc-3.4.2/* src/
-rm -rf petsc-3.4.2
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
 
 #configure
Index: /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 16559)
+++ /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 16560)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.2 src
+rm -rf install petsc-3.4.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.2.tar.gz
-mv petsc-3.4.2/* src/
-rm -rf petsc-3.4.2
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
 
 #configure
Index: /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh	(revision 16560)
+++ /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh	(revision 16560)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/mvapich2/1.4.1/gcc.sles11/lib/libmpich.a"\
+ --with-mpi-include="/nasa/mvapich2/1.4.1/gcc.sles11/include"\
+ --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpich" \
+ --FOPTFLAGS="-lmpich" \
+ --CXXOPTFLAGS="-lmpich"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load mpi-mvapich2/1.4.1/gcc
+module load gcc/4.4.4
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh	(revision 16560)
+++ /issm/trunk/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh	(revision 16560)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/mvapich2/1.6.sles11/gcc/lib/libmpich.a"\
+ --with-mpi-include="/nasa/mvapich2/1.6.sles11/gcc/include" \
+ --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpich" \
+ --FOPTFLAGS="-lmpich" \
+ --CXXOPTFLAGS="-lmpich"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load mpi-mvapich2/1.6/gcc
+module load gcc/4.7.0
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 16559)
+++ /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 16560)
@@ -2,14 +2,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.2 src
+rm -rf install petsc-3.4.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.2.tar.gz
-mv petsc-3.4.2/* src/
-rm -rf petsc-3.4.2
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
 
 #configure
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 16559)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 16560)
@@ -15,4 +15,5 @@
 echo "\"ISSM's objects begin" >> temp
 find ../../../../../src/c/classes -name "*.cpp" -o -name "*.h" | sed -e "s/\// /g" -e "s/\.cpp//" -e "s/\.h//" | awk '{print  $(NF)}' | sort | uniq | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
+find ../../../../../src/c/analyses -name "*Analysis.h" | sed -e "s/\// /g" -e "s/\.cpp//" -e "s/\.h//" | awk '{print  $(NF)}' | sort | uniq | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
 echo "\"ISSM's objects end" >> temp
 cat c.vim | sed "1,/ISSM's objects end/d" >> temp
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 16559)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 16560)
@@ -410,5 +410,4 @@
 
 "ISSM's objects begin
-syn keyword cType BoolElementResult
 syn keyword cType BoolInput
 syn keyword cType BoolParam
@@ -420,7 +419,7 @@
 syn keyword cType DataSetParam
 syn keyword cType DatasetInput
+syn keyword cType Definition
 syn keyword cType DependentObject
 syn keyword cType DofIndexing
-syn keyword cType DoubleElementResult
 syn keyword cType DoubleInput
 syn keyword cType DoubleMatArrayParam
@@ -432,5 +431,4 @@
 syn keyword cType ElementHook
 syn keyword cType ElementMatrix
-syn keyword cType ElementResult
 syn keyword cType ElementVector
 syn keyword cType Elements
@@ -441,4 +439,5 @@
 syn keyword cType Friction
 syn keyword cType GaussPenta
+syn keyword cType GaussSeg
 syn keyword cType GaussTria
 syn keyword cType GaussianVariogram
@@ -458,5 +457,5 @@
 syn keyword cType Load
 syn keyword cType Loads
-syn keyword cType Matdamageice
+syn keyword cType Massfluxatgate
 syn keyword cType Material
 syn keyword cType Materials
@@ -474,10 +473,8 @@
 syn keyword cType Param
 syn keyword cType Parameters
-syn keyword cType Patch
 syn keyword cType Pengrid
 syn keyword cType Penpair
 syn keyword cType Penta
 syn keyword cType PentaInput
-syn keyword cType PentaP1ElementResult
 syn keyword cType PentaRef
 syn keyword cType PowerVariogram
@@ -487,4 +484,7 @@
 syn keyword cType RiftStruct
 syn keyword cType Riftfront
+syn keyword cType Seg
+syn keyword cType SegInput
+syn keyword cType SegRef
 syn keyword cType Segment
 syn keyword cType SpcDynamic
@@ -498,5 +498,4 @@
 syn keyword cType Tria
 syn keyword cType TriaInput
-syn keyword cType TriaP1ElementResult
 syn keyword cType TriaRef
 syn keyword cType Update
@@ -509,4 +508,31 @@
 syn keyword cType krigingobjects
 syn keyword cType matrixobjects
+syn keyword cType AdjointBalancethicknessAnalysis
+syn keyword cType AdjointHorizAnalysis
+syn keyword cType Analysis
+syn keyword cType BalancethicknessAnalysis
+syn keyword cType BalancethicknessSoftAnalysis
+syn keyword cType BalancevelocityAnalysis
+syn keyword cType DamageEvolutionAnalysis
+syn keyword cType EnthalpyAnalysis
+syn keyword cType EnumToAnalysis
+syn keyword cType ExtrudeFromBaseAnalysis
+syn keyword cType ExtrudeFromTopAnalysis
+syn keyword cType FreeSurfaceBaseAnalysis
+syn keyword cType FreeSurfaceTopAnalysis
+syn keyword cType GiaAnalysis
+syn keyword cType HydrologyDCEfficientAnalysis
+syn keyword cType HydrologyDCInefficientAnalysis
+syn keyword cType HydrologyShreveAnalysis
+syn keyword cType L2ProjectionBaseAnalysis
+syn keyword cType MasstransportAnalysis
+syn keyword cType MeltingAnalysis
+syn keyword cType MeshdeformationAnalysis
+syn keyword cType SmoothedSurfaceSlopeXAnalysis
+syn keyword cType SmoothedSurfaceSlopeYAnalysis
+syn keyword cType StressbalanceAnalysis
+syn keyword cType StressbalanceSIAAnalysis
+syn keyword cType StressbalanceVerticalAnalysis
+syn keyword cType ThermalAnalysis
 "ISSM's objects end
 "ISSM's Enums begin
@@ -531,4 +557,10 @@
 syn keyword cConstant AutodiffMassFluxSegmentsPresentEnum
 syn keyword cConstant AutodiffKeepEnum
+syn keyword cConstant AutodiffObufsizeEnum
+syn keyword cConstant AutodiffLbufsizeEnum
+syn keyword cConstant AutodiffCbufsizeEnum
+syn keyword cConstant AutodiffTbufsizeEnum
+syn keyword cConstant AutodiffGcTriggerRatioEnum
+syn keyword cConstant AutodiffGcTriggerMaxSizeEnum
 syn keyword cConstant BalancethicknessSpcthicknessEnum
 syn keyword cConstant BalancethicknessStabilizationEnum
@@ -544,11 +576,10 @@
 syn keyword cConstant DependentObjectEnum
 syn keyword cConstant StressbalanceAbstolEnum
-syn keyword cConstant StressbalanceIcefrontEnum
 syn keyword cConstant StressbalanceIsnewtonEnum
 syn keyword cConstant StressbalanceMaxiterEnum
-syn keyword cConstant StressbalanceNumRequestedOutputsEnum
 syn keyword cConstant StressbalancePenaltyFactorEnum
 syn keyword cConstant StressbalanceReferentialEnum
 syn keyword cConstant StressbalanceReltolEnum
+syn keyword cConstant StressbalanceNumRequestedOutputsEnum
 syn keyword cConstant StressbalanceRequestedOutputsEnum
 syn keyword cConstant StressbalanceRestolEnum
@@ -620,5 +651,4 @@
 syn keyword cConstant HydrologyEfficientEnum
 syn keyword cConstant HydrologySedimentKmaxEnum
-syn keyword cConstant BasisIntegralEnum
 syn keyword cConstant WaterTransferEnum
 syn keyword cConstant IndependentObjectEnum
@@ -627,5 +657,4 @@
 syn keyword cConstant InversionCostFunctionsCoefficientsEnum
 syn keyword cConstant InversionCostFunctionsEnum
-syn keyword cConstant InversionGradientOnlyEnum
 syn keyword cConstant InversionGradientScalingEnum
 syn keyword cConstant InversionIscontrolEnum
@@ -640,13 +669,9 @@
 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 MaskVertexonfloatingiceEnum
-syn keyword cConstant MaskVertexongroundediceEnum
 syn keyword cConstant MaskIceLevelsetEnum
+syn keyword cConstant QmuMaskIceLevelsetEnum
 syn keyword cConstant MaterialsBetaEnum
 syn keyword cConstant MaterialsHeatcapacityEnum
@@ -658,6 +683,21 @@
 syn keyword cConstant MaterialsRheologyLawEnum
 syn keyword cConstant MaterialsRheologyNEnum
-syn keyword cConstant MaterialsRheologyZEnum
-syn keyword cConstant MaterialsRheologyZbarEnum
+syn keyword cConstant DamageDEnum
+syn keyword cConstant QmuDamageDEnum
+syn keyword cConstant DamageDbarEnum
+syn keyword cConstant DamageLawEnum
+syn keyword cConstant DamageC1Enum
+syn keyword cConstant DamageC2Enum
+syn keyword cConstant DamageC3Enum
+syn keyword cConstant DamageC4Enum
+syn keyword cConstant DamageHealingEnum
+syn keyword cConstant DamageStressThresholdEnum
+syn keyword cConstant DamageStabilizationEnum
+syn keyword cConstant DamagePenaltyThresholdEnum
+syn keyword cConstant DamagePenaltyLockEnum
+syn keyword cConstant DamagePenaltyFactorEnum
+syn keyword cConstant DamageMaxiterEnum
+syn keyword cConstant DamageSpcdamageEnum
+syn keyword cConstant DamageMaxDamageEnum
 syn keyword cConstant MaterialsRhoIceEnum
 syn keyword cConstant MaterialsRhoWaterEnum
@@ -671,5 +711,4 @@
 syn keyword cConstant MaterialsMantleDensityEnum
 syn keyword cConstant MeshAverageVertexConnectivityEnum
-syn keyword cConstant MeshDimensionEnum
 syn keyword cConstant MeshElementonbedEnum
 syn keyword cConstant MeshElementonsurfaceEnum
@@ -688,4 +727,8 @@
 syn keyword cConstant MeshYEnum
 syn keyword cConstant MeshZEnum
+syn keyword cConstant MeshTypeEnum
+syn keyword cConstant Mesh2DhorizontalEnum
+syn keyword cConstant Mesh2DverticalEnum
+syn keyword cConstant Mesh3DEnum
 syn keyword cConstant MiscellaneousNameEnum
 syn keyword cConstant MasstransportHydrostaticAdjustmentEnum
@@ -713,5 +756,4 @@
 syn keyword cConstant SettingsLowmemEnum
 syn keyword cConstant SettingsOutputFrequencyEnum
-syn keyword cConstant SettingsResultsAsPatchesEnum
 syn keyword cConstant SettingsWaitonlockEnum
 syn keyword cConstant SurfaceforcingsDelta18oEnum
@@ -742,4 +784,6 @@
 syn keyword cConstant SurfaceforcingsBPosEnum
 syn keyword cConstant SurfaceforcingsBNegEnum
+syn keyword cConstant ThermalIsenthalpyEnum
+syn keyword cConstant ThermalIsdynamicbasalspcEnum
 syn keyword cConstant ThermalMaxiterEnum
 syn keyword cConstant ThermalPenaltyFactorEnum
@@ -748,5 +792,6 @@
 syn keyword cConstant ThermalSpctemperatureEnum
 syn keyword cConstant ThermalStabilizationEnum
-syn keyword cConstant ThermalIsenthalpyEnum
+syn keyword cConstant ThermalNumRequestedOutputsEnum
+syn keyword cConstant ThermalRequestedOutputsEnum
 syn keyword cConstant GiaMantleViscosityEnum
 syn keyword cConstant GiaLithosphereThicknessEnum
@@ -762,4 +807,5 @@
 syn keyword cConstant TransientIsthermalEnum
 syn keyword cConstant TransientIsgiaEnum
+syn keyword cConstant TransientIsdamageEnum
 syn keyword cConstant TransientNumRequestedOutputsEnum
 syn keyword cConstant TransientRequestedOutputsEnum
@@ -769,7 +815,5 @@
 syn keyword cConstant AdjointBalancethicknessAnalysisEnum
 syn keyword cConstant AdjointHorizAnalysisEnum
-syn keyword cConstant AdjointSolutionEnum
 syn keyword cConstant AnalysisCounterEnum
-syn keyword cConstant NoneAnalysisEnum
 syn keyword cConstant DefaultAnalysisEnum
 syn keyword cConstant BalancethicknessAnalysisEnum
@@ -777,8 +821,10 @@
 syn keyword cConstant BalancethicknessSoftAnalysisEnum
 syn keyword cConstant BalancethicknessSoftSolutionEnum
-syn keyword cConstant BedSlopeAnalysisEnum
+syn keyword cConstant BalancevelocityAnalysisEnum
+syn keyword cConstant BalancevelocitySolutionEnum
+syn keyword cConstant L2ProjectionBaseAnalysisEnum
 syn keyword cConstant BedSlopeSolutionEnum
-syn keyword cConstant BedSlopeXAnalysisEnum
-syn keyword cConstant BedSlopeYAnalysisEnum
+syn keyword cConstant DamageEvolutionSolutionEnum
+syn keyword cConstant DamageEvolutionAnalysisEnum
 syn keyword cConstant StressbalanceAnalysisEnum
 syn keyword cConstant StressbalanceSIAAnalysisEnum
@@ -786,5 +832,4 @@
 syn keyword cConstant StressbalanceVerticalAnalysisEnum
 syn keyword cConstant EnthalpyAnalysisEnum
-syn keyword cConstant EnthalpySolutionEnum
 syn keyword cConstant FlaimAnalysisEnum
 syn keyword cConstant FlaimSolutionEnum
@@ -798,9 +843,11 @@
 syn keyword cConstant FreeSurfaceBaseAnalysisEnum
 syn keyword cConstant FreeSurfaceTopAnalysisEnum
+syn keyword cConstant ExtrudeFromBaseAnalysisEnum
+syn keyword cConstant ExtrudeFromTopAnalysisEnum
 syn keyword cConstant SteadystateSolutionEnum
-syn keyword cConstant SurfaceSlopeAnalysisEnum
+syn keyword cConstant L2ProjectionTopAnalysisEnum
 syn keyword cConstant SurfaceSlopeSolutionEnum
-syn keyword cConstant SurfaceSlopeXAnalysisEnum
-syn keyword cConstant SurfaceSlopeYAnalysisEnum
+syn keyword cConstant SmoothedSurfaceSlopeXAnalysisEnum
+syn keyword cConstant SmoothedSurfaceSlopeYAnalysisEnum
 syn keyword cConstant ThermalAnalysisEnum
 syn keyword cConstant ThermalSolutionEnum
@@ -808,4 +855,6 @@
 syn keyword cConstant GiaSolutionEnum
 syn keyword cConstant GiaAnalysisEnum
+syn keyword cConstant MeshdeformationSolutionEnum
+syn keyword cConstant MeshdeformationAnalysisEnum
 syn keyword cConstant ApproximationEnum
 syn keyword cConstant NoneApproximationEnum
@@ -835,5 +884,4 @@
 syn keyword cConstant ControlInputEnum
 syn keyword cConstant DatasetInputEnum
-syn keyword cConstant DofIndexingEnum
 syn keyword cConstant DoubleInputEnum
 syn keyword cConstant DataSetParamEnum
@@ -843,19 +891,14 @@
 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 InputToExtrudeEnum
+syn keyword cConstant InputToL2ProjectEnum
 syn keyword cConstant IntParamEnum
 syn keyword cConstant IntVecParamEnum
 syn keyword cConstant TransientParamEnum
-syn keyword cConstant IceFrontTypeEnum
-syn keyword cConstant SSA2dIceFrontEnum
-syn keyword cConstant SSA3dIceFrontEnum
 syn keyword cConstant MaticeEnum
-syn keyword cConstant MatdamageiceEnum
 syn keyword cConstant MatparEnum
 syn keyword cConstant NodeEnum
@@ -863,6 +906,4 @@
 syn keyword cConstant NumericalfluxTypeEnum
 syn keyword cConstant ParamEnum
-syn keyword cConstant L1L2IceFrontEnum
-syn keyword cConstant HOIceFrontEnum
 syn keyword cConstant PengridEnum
 syn keyword cConstant PenpairEnum
@@ -880,7 +921,8 @@
 syn keyword cConstant SpcStaticEnum
 syn keyword cConstant SpcTransientEnum
-syn keyword cConstant FSIceFrontEnum
 syn keyword cConstant StringArrayParamEnum
 syn keyword cConstant StringParamEnum
+syn keyword cConstant SegEnum
+syn keyword cConstant SegInputEnum
 syn keyword cConstant TriaEnum
 syn keyword cConstant TriaInputEnum
@@ -903,5 +945,4 @@
 syn keyword cConstant BedSlopeYEnum
 syn keyword cConstant BoundaryEnum
-syn keyword cConstant ConstantEnum
 syn keyword cConstant ConvergedEnum
 syn keyword cConstant FillEnum
@@ -911,8 +952,6 @@
 syn keyword cConstant InternalEnum
 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
@@ -940,5 +979,4 @@
 syn keyword cConstant SurfaceSlopeYEnum
 syn keyword cConstant TemperatureEnum
-syn keyword cConstant TemperatureOldEnum
 syn keyword cConstant TemperaturePicardEnum
 syn keyword cConstant ThicknessAbsMisfitEnum
@@ -964,5 +1002,4 @@
 syn keyword cConstant ThicknessAlongGradientEnum
 syn keyword cConstant ThicknessAcrossGradientEnum
-syn keyword cConstant StepResponsesEnum
 syn keyword cConstant IntMatParamEnum
 syn keyword cConstant RheologyBbarAbsGradientEnum
@@ -972,5 +1009,4 @@
 syn keyword cConstant WatercolumnEnum
 syn keyword cConstant BasalFrictionEnum
-syn keyword cConstant BasalMeltrateEnum
 syn keyword cConstant ViscousHeatingEnum
 syn keyword cConstant QmuTemperatureEnum
@@ -1001,20 +1037,18 @@
 syn keyword cConstant TaylorHoodEnum
 syn keyword cConstant SaveResultsEnum
-syn keyword cConstant BoolElementResultEnum
 syn keyword cConstant BoolExternalResultEnum
-syn keyword cConstant DoubleElementResultEnum
 syn keyword cConstant DoubleExternalResultEnum
 syn keyword cConstant DoubleMatExternalResultEnum
 syn keyword cConstant IntExternalResultEnum
 syn keyword cConstant JEnum
-syn keyword cConstant PatchEnum
-syn keyword cConstant PatchNodesEnum
-syn keyword cConstant PatchVerticesEnum
-syn keyword cConstant PentaP1ElementResultEnum
 syn keyword cConstant StringExternalResultEnum
 syn keyword cConstant StepEnum
 syn keyword cConstant TimeEnum
-syn keyword cConstant TriaP1ElementResultEnum
 syn keyword cConstant WaterColumnOldEnum
+syn keyword cConstant OutputdefinitionEnum
+syn keyword cConstant OutputdefinitionListEnum
+syn keyword cConstant MassfluxatgateEnum
+syn keyword cConstant MassfluxatgateNameEnum
+syn keyword cConstant MassfluxatgateSegmentsEnum
 syn keyword cConstant MinVelEnum
 syn keyword cConstant MaxVelEnum
@@ -1029,4 +1063,5 @@
 syn keyword cConstant MaxAbsVzEnum
 syn keyword cConstant IceVolumeEnum
+syn keyword cConstant IceVolumeAboveFloatationEnum
 syn keyword cConstant TotalSmbEnum
 syn keyword cConstant AbsoluteEnum
@@ -1038,4 +1073,5 @@
 syn keyword cConstant SubelementMigration2Enum
 syn keyword cConstant MaskGroundediceLevelsetEnum
+syn keyword cConstant QmuMaskGroundediceLevelsetEnum
 syn keyword cConstant FSSolverEnum
 syn keyword cConstant AdjointEnum
@@ -1074,13 +1110,13 @@
 syn keyword cConstant DenseEnum
 syn keyword cConstant MpiDenseEnum
+syn keyword cConstant MpiSparseEnum
 syn keyword cConstant SeqEnum
 syn keyword cConstant MpiEnum
+syn keyword cConstant MumpsEnum
+syn keyword cConstant GslEnum
 syn keyword cConstant OptionEnum
 syn keyword cConstant GenericOptionEnum
 syn keyword cConstant OptionCellEnum
-syn keyword cConstant OptionCharEnum
 syn keyword cConstant OptionStructEnum
-syn keyword cConstant OptionDoubleEnum
-syn keyword cConstant OptionLogicalEnum
 syn keyword cConstant PatersonEnum
 syn keyword cConstant ArrheniusEnum
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 16559)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 16560)
@@ -155,6 +155,6 @@
 " and here some nice options for cindenting
 set cinoptions={.5s,+.5s,t0,n-2,p2s,(03s,=.5s,>1s,=1s,:1s 
-" pound sign identation
-inoremap # X<c-h>#
+" hash sign identation
+set cinkeys-=0#
 " ----------------------------------------------------------------------}}}
 " TEX special{{{
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 16559)
+++ /issm/trunk/m4/issm_options.m4	(revision 16560)
@@ -8,4 +8,16 @@
 
 	dnl ISSM's internal options
+	dnl Build info{{{
+	AC_PATH_PROGS(DATE, date)
+	AC_MSG_CHECKING(for build date)
+	dnl system checks require uname
+	if test "$DATE" ; then
+		PACKAGE_DATE=`date`
+	else
+		PACKAGE_DATE="unknown date"
+	fi
+	AC_DEFINE_UNQUOTED(PACKAGE_BUILD_DATE,"$PACKAGE_DATE", Build date)
+	AC_MSG_RESULT($PACKAGE_DATE)
+	dnl }}}
 	dnl Debugging {{{
 	AC_ARG_ENABLE([debugging],                                        dnl feature
@@ -106,4 +118,9 @@
 			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
 			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+		elif test $VENDOR = intel-pleiades-gcc; then
+			export CC=gcc
+			export CXX=g++
+			export CXXFLAGS=" -g -O2 "
+			export CFLAGS=" -g -O2 "
         else
 		AC_MSG_ERROR([unknown compiler vendor!])
@@ -472,4 +489,5 @@
 	fi
 	AC_MSG_RESULT($HAVE_SCOTCH)
+	AM_CONDITIONAL([SCOTCH],[test x$HAVE_SCOTCH = xyes])
 	
 	dnl scotch libraries
@@ -1699,4 +1717,22 @@
 	AC_MSG_RESULT($HAVE_BALANCED)
 	dnl }}}
+	dnl with-damage{{{
+	AC_ARG_WITH([damage],
+		AS_HELP_STRING([--with-damage = YES], [compile with damage capabilities (default is yes)]),
+		[DAMAGE=$withval],[DAMAGE=yes]) 
+	AC_MSG_CHECKING(for damage capability compilation)
+
+	if test "x$DAMAGE" = "xyes"; then
+
+		dnl defaults
+		HAVE_DAMAGE=yes
+
+		AC_DEFINE([_HAVE_DAMAGE_],[1],[with damage capability])
+	else
+		HAVE_DAMAGE=no
+	fi
+	AM_CONDITIONAL([DAMAGE], [test x$HAVE_DAMAGE = xyes])
+	AC_MSG_RESULT($HAVE_DAMAGE)
+	dnl }}}
 	dnl with-responses{{{
 	AC_ARG_WITH([responses],
@@ -1735,4 +1771,22 @@
 	AC_MSG_RESULT($HAVE_SLOPE)
 	dnl }}}
+	dnl with-meshdeformation{{{
+		AC_ARG_WITH([meshdeformation],
+					AS_HELP_STRING([--with-meshdeformation = YES], [compile with meshdeformation capabilities (default is yes)]),
+					[MESHDEFORMATION=$withval],[MESHDEFORMATION=yes]) 
+		  AC_MSG_CHECKING(for meshdeformation capability compilation)
+
+		  if test "x$MESHDEFORMATION" = "xyes"; then
+
+			dnl defaults
+			  HAVE_MESHDEFORMATION=yes
+
+			  AC_DEFINE([_HAVE_MESHDEFORMATION_],[1],[with meshdeformation capability])
+		  else
+				HAVE_MESHDEFORMATION=no
+		  fi
+	  AM_CONDITIONAL([MESHDEFORMATION], [test x$HAVE_MESHDEFORMATION = xyes])
+	  AC_MSG_RESULT($HAVE_MESHDEFORMATION)
+	  dnl }}}
 	dnl with-groundingline{{{
 	AC_ARG_WITH([groundingline],
@@ -1910,8 +1964,7 @@
 		;;
 		esac
-
 		AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
-		AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
-	fi
+	fi
+	AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
 	AC_SUBST([MULTITHREADINGLIB])
 	AC_MSG_RESULT($NUMTHREADS_VALUE) 
Index: /issm/trunk/scripts/BinRead.py
===================================================================
--- /issm/trunk/scripts/BinRead.py	(revision 16559)
+++ /issm/trunk/scripts/BinRead.py	(revision 16560)
@@ -123,4 +123,5 @@
 	sent.
 	"""
+	from MatlabFuncs import *
 
 	if   strcmpi(format,'Boolean'):
Index: /issm/trunk/scripts/cppcheck.sh
===================================================================
--- /issm/trunk/scripts/cppcheck.sh	(revision 16559)
+++ /issm/trunk/scripts/cppcheck.sh	(revision 16560)
@@ -1,3 +1,7 @@
 #!/bin/bash
 
-cppcheck -j 8 --include=$ISSM_DIR/config.h --enable=all $ISSM_DIR/src/c 2> CPPCHECK.err
+#comprehensive check, except unusedFunction
+#cppcheck -j 32 --include=$ISSM_DIR/config.h -DHAVE_CONFIG_H -D_HAVE_ADOLC_ -D_HAVE_DAKOTA_ --enable=all $ISSM_DIR/src/c 2> CPPCHECK.err
+
+#unused function only (slow)
+cppcheck --include=$ISSM_DIR/config.h -DHAVE_CONFIG_H -D_HAVE_ADOLC_ -D_HAVE_DAKOTA_ --enable=unusedFunction $ISSM_DIR/src 2> CPPCHECK.err
Index: /issm/trunk/scripts/ol.m
===================================================================
--- /issm/trunk/scripts/ol.m	(revision 16560)
+++ /issm/trunk/scripts/ol.m	(revision 16560)
@@ -0,0 +1,1 @@
+system('ol');
Index: /issm/trunk/scripts/tai
===================================================================
--- /issm/trunk/scripts/tai	(revision 16559)
+++ /issm/trunk/scripts/tai	(revision 16560)
@@ -6,4 +6,4 @@
 
 DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
-echo "Execution idrectory: $DIR"
+echo "Execution directory: $DIR"
 tail -f $DIR/*.outlog
Index: /issm/trunk/src/c/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/CMakeLists.txt	(revision 16559)
+++ /issm/trunk/src/c/CMakeLists.txt	(revision 16560)
@@ -9,5 +9,4 @@
                           $ENV{ISSM_DIR}/src/c/classes 
                           $ENV{ISSM_DIR}/src/c/classes/Options 
-                          $ENV{ISSM_DIR}/src/c/classes/ElementResults 
                           $ENV{ISSM_DIR}/src/c/classes/ExternalResults 
                           $ENV{ISSM_DIR}/src/c/classes/Elements 
@@ -57,5 +56,4 @@
                           $ENV{ISSM_DIR}/src/c/modules/GetVectorFromInputsx 
                           $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorx 
-                          $ENV{ISSM_DIR}/src/c/modules/InputArtificialNoisex 
                           $ENV{ISSM_DIR}/src/c/modules/ConfigureObjectsx 
                           $ENV{ISSM_DIR}/src/c/modules/ComputeBasalStressx 
@@ -74,6 +72,5 @@
                           $ENV{ISSM_DIR}/src/c/modules/VecMergex 
                           $ENV{ISSM_DIR}/src/c/modules/Mergesolutionfromftogx 
-                          $ENV{ISSM_DIR}/src/c/modules/InputToResultx 
-                          $ENV{ISSM_DIR}/src/c/analyses 
+                          $ENV{ISSM_DIR}/src/c/cores 
                           $ENV{ISSM_DIR}/src/c/solutionsequences 
                           $ENV{ISSM_DIR}/src/c/solutionsequences)
@@ -97,8 +94,4 @@
 					./classes/Vertex.cpp
 					./classes/Hook.cpp
-					./classes/Patch.cpp
-					./classes/ElementResults/DoubleElementResult.cpp
-					./classes/ElementResults/TriaP1ElementResult.cpp
-					./classes/ElementResults/BoolElementResult.cpp
 					./classes/ExternalResults/Results.cpp
 					./classes/Elements/Elements.cpp
@@ -174,5 +167,4 @@
 					./toolkits/ToolkitOptions.cpp
 					./modules/ModelProcessorx/ModelProcessorx.cpp
-					./modules/ModelProcessorx/DistributeNumDofs.cpp
 					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
 					./modules/ModelProcessorx/NodesPartitioning.cpp
@@ -206,5 +198,4 @@
 					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
-					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp
 					./modules/ComputeBasalStressx/ComputeBasalStressx.cpp
@@ -222,13 +213,12 @@
 					./modules/VecMergex/VecMergex.cpp
 					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
-					./modules/InputToResultx/InputToResultx.cpp
-					./analyses/ProcessArguments.cpp
-					./analyses/ResetBoundaryConditions.cpp
-					./analyses/AnalysisConfiguration.cpp
-					./analyses/WrapperCorePointerFromSolutionEnum.cpp
-					./analyses/CorePointerFromSolutionEnum.cpp
-					./analyses/EnvironmentInit.cpp
-					./analyses/EnvironmentFinalize.cpp
-					./analyses/ad_core.cpp
+					./cores/ProcessArguments.cpp
+					./cores/ResetBoundaryConditions.cpp
+					./cores/AnalysisConfiguration.cpp
+					./cores/WrapperCorePointerFromSolutionEnum.cpp
+					./cores/CorePointerFromSolutionEnum.cpp
+					./cores/EnvironmentInit.cpp
+					./cores/EnvironmentFinalize.cpp
+					./cores/ad_core.cpp
 					./solutionsequences/solutionsequence_linear.cpp
 					./solutionsequences/solutionsequence_nonlinear.cpp
@@ -247,13 +237,13 @@
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
 					  				  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
-					  ./analyses/dakota_core.cpp
-					  				  ./analyses/DakotaSpawnCore.cpp)
+					  ./cores/dakota_core.cpp
+					  				  ./cores/DakotaSpawnCore.cpp)
 #}}}
 #Transient sources  {{{
 set(transient_sources ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp 
-							./analyses/transient_core.cpp)
+							./cores/transient_core.cpp)
 #}}}
 #Steadystate sources  {{{
-set(steadystate_sources ./analyses/steadystate_core.cpp)
+set(steadystate_sources ./cores/steadystate_core.cpp)
 #}}}
 #Prognostic sources  {{{
@@ -262,5 +252,5 @@
 					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
 					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
-							./analyses/prognostic_core.cpp)
+							./cores/prognostic_core.cpp)
 #}}}
 #Thermal sources  {{{
@@ -280,6 +270,5 @@
 					   ./modules/ConstraintsStatex/ThermalIsPresent.cpp
 					   ./modules/ResetConstraintsx/ThermalConstraintsReset.cpp 
-					   ./analyses/thermal_core.cpp
-					   ./analyses/enthalpy_core.cpp
+					   ./cores/thermal_core.cpp
 					   ./solutionsequences/solutionsequence_thermal_nonlinear.cpp)
 #}}}
@@ -308,11 +297,11 @@
 					  ./shared/Numerics/BrentSearch.cpp
 					  ./shared/Numerics/OptimalSearch.cpp 
-					  ./analyses/control_core.cpp
-					  ./analyses/controltao_core.cpp
-					  ./analyses/objectivefunction.cpp
-					  ./analyses/gradient_core.cpp
-					  ./analyses/adjointdiagnostic_core.cpp
-					  ./analyses/adjointbalancethickness_core.cpp
-					  ./analyses/AdjointCorePointerFromSolutionEnum.cpp
+					  ./cores/control_core.cpp
+					  ./cores/controltao_core.cpp
+					  ./cores/objectivefunction.cpp
+					  ./cores/gradient_core.cpp
+					  ./cores/adjointdiagnostic_core.cpp
+					  ./cores/adjointbalancethickness_core.cpp
+					  ./cores/AdjointCorePointerFromSolutionEnum.cpp
 					  ./solutionsequences/solutionsequence_adjoint_linear.cpp)
 #}}}
@@ -333,5 +322,5 @@
 							./modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp 
 							./modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp 
-							./analyses/hydrology_core.cpp
+							./cores/hydrology_core.cpp
 							./solutionsequences/solutionsequence_hydro_nonlinear.cpp)
 #}}}
@@ -349,5 +338,5 @@
 					      ./modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp 
 							./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp 
-							./analyses/diagnostic_core.cpp
+							./cores/diagnostic_core.cpp
 							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp)
 #}}}
@@ -357,6 +346,6 @@
 					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
 						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
-						 ./analyses/balancethickness_core.cpp 
-						 ./analyses/dummy_core.cpp)
+						 ./cores/balancethickness_core.cpp 
+						 ./cores/dummy_core.cpp)
 #}}}
 #Slope sources  {{{
@@ -369,9 +358,9 @@
 					  ./modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
 					  ./modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
-					  ./analyses/surfaceslope_core.cpp
-					  ./analyses/bedslope_core.cpp)
+					  ./cores/surfaceslope_core.cpp
+					  ./cores/bedslope_core.cpp)
 #}}}
 #Gia sources  {{{
-set(gia_sources  ./analyses/gia_core.cpp
+set(gia_sources  ./cores/gia_core.cpp
 					./modules/ModelProcessorx/Gia/UpdateElementsGia.cpp
 					./modules/ModelProcessorx/Gia/CreateNodesGia.cpp 
@@ -401,5 +390,4 @@
 #3D sources  {{{
 set(threed_sources 			     ./classes/gauss/GaussPenta.cpp
-				     			     ./classes/ElementResults/PentaP1ElementResult.cpp
 				     			     ./classes/Inputs/PentaInput.cpp
 				     			     ./classes/Elements/Penta.cpp
@@ -515,7 +503,4 @@
 					./toolkits/petsc/patches/NewMat.cpp
 					./toolkits/petsc/patches/VecFree.cpp
-					./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp
-					./toolkits/petsc/patches/PetscVectorToDoubleVector.cpp
-					./toolkits/petsc/patches/VecDuplicatePatch.cpp
 					./toolkits/petsc/patches/KSPFree.cpp
 					./toolkits/petsc/patches/MatFree.cpp
@@ -549,6 +534,5 @@
 # API Print {{{
 if(NOT PYTHON AND NOT MATLAB)
-    add_library(ISSMOverload STATIC ./shared/String/stricmp.cpp
-            ./shared/String/ApiPrintf.cpp)
+    add_library(ISSMOverload STATIC ./shared/String/ApiPrintf.cpp)
     list(APPEND issm_deps ISSMOverload)
 else(NOT PYTHON AND NOT MATLAB)
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 16559)
+++ /issm/trunk/src/c/Makefile.am	(revision 16560)
@@ -25,4 +25,6 @@
 					./datastructures/datastructures.h\
 					./classes/classes.h\
+					./classes/gauss/GaussSeg.h\
+					./classes/gauss/GaussSeg.cpp\
 					./classes/gauss/GaussTria.h\
 					./classes/gauss/GaussTria.cpp\
@@ -61,13 +63,4 @@
 					./classes/Hook.h\
 					./classes/Hook.cpp\
-					./classes/Patch.h\
-					./classes/Patch.cpp\
-					./classes/ElementResults/ElementResultLocal.h\
-					./classes/ElementResults/DoubleElementResult.h\
-					./classes/ElementResults/DoubleElementResult.cpp\
-					./classes/ElementResults/TriaP1ElementResult.h\
-					./classes/ElementResults/TriaP1ElementResult.cpp\
-					./classes/ElementResults/BoolElementResult.h\
-					./classes/ElementResults/BoolElementResult.cpp\
 					./classes/ExternalResults/Results.h\
 					./classes/ExternalResults/Results.cpp\
@@ -78,4 +71,8 @@
 					./classes/Elements/ElementHook.h\
 					./classes/Elements/ElementHook.cpp\
+					./classes/Elements/Seg.h\
+					./classes/Elements/Seg.cpp\
+					./classes/Elements/SegRef.h\
+					./classes/Elements/SegRef.cpp\
 					./classes/Elements/Tria.h\
 					./classes/Elements/Tria.cpp\
@@ -86,4 +83,6 @@
 					./classes/Inputs/Input.h\
 					./classes/Inputs/InputLocal.h\
+					./classes/Inputs/SegInput.h\
+					./classes/Inputs/SegInput.cpp\
 					./classes/Inputs/TriaInput.h\
 					./classes/Inputs/TriaInput.cpp\
@@ -100,6 +99,4 @@
 					./classes/Materials/Matice.h\
 					./classes/Materials/Matice.cpp\
-					./classes/Materials/Matdamageice.h\
-					./classes/Materials/Matdamageice.cpp\
 					./classes/Materials/Matpar.h\
 					./classes/Materials/Matpar.cpp\
@@ -199,5 +196,4 @@
 					./shared/Exceptions/exceptions.h\
 					./shared/Exceptions/Exceptions.cpp\
-					./shared/Exceptions/exprintf.cpp\
 					./shared/Sorting/binary_search.cpp\
 					./shared/Sorting/sorting.h\
@@ -224,4 +220,5 @@
 					./toolkits/issm/IssmSolver.h\
 					./toolkits/issm/IssmSolver.cpp\
+					./toolkits/issm/SparseRow.h\
 					./toolkits/issm/Bucket.h\
 					./toolkits/mpi/issmmpi.h\
@@ -245,12 +242,8 @@
 					./modules/ModelProcessorx/ModelProcessorx.h\
 					./modules/ModelProcessorx/ModelProcessorx.cpp\
-					./modules/ModelProcessorx/DistributeNumDofs.cpp\
 					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
 					./modules/ModelProcessorx/NodesPartitioning.cpp\
 					./modules/ModelProcessorx/EdgesPartitioning.cpp\
 					./modules/ModelProcessorx/FacesPartitioning.cpp\
-					./modules/ModelProcessorx/SortDataSets.cpp\
-					./modules/ModelProcessorx/UpdateCounters.cpp\
-					./modules/ModelProcessorx/CreateDataSets.cpp\
 					./modules/ModelProcessorx/CreateParameters.cpp\
 					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
@@ -301,6 +294,4 @@
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
-					./modules/InputArtificialNoisex/InputArtificialNoisex.h\
-					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
@@ -313,6 +304,4 @@
 					./modules/PositiveDegreeDayx/PositiveDegreeDayx.h\
 					./modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp\
-					./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h\
-					./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp\
 					./modules/Delta18oParameterizationx/Delta18oParameterizationx.h\
 					./modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp\
@@ -337,14 +326,15 @@
 					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
 					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
-					./modules/InputToResultx/InputToResultx.cpp\
-					./modules/InputToResultx/InputToResultx.h\
-					./analyses/ProcessArguments.cpp\
-					./analyses/ResetBoundaryConditions.cpp\
-					./analyses/AnalysisConfiguration.cpp\
-					./analyses/WrapperCorePointerFromSolutionEnum.cpp\
-					./analyses/CorePointerFromSolutionEnum.cpp\
-					./analyses/EnvironmentInit.cpp\
-					./analyses/EnvironmentFinalize.cpp\
-					./analyses/ad_core.cpp\
+					./cores/ProcessArguments.cpp\
+					./cores/ResetBoundaryConditions.cpp\
+					./cores/AnalysisConfiguration.cpp\
+					./cores/WrapperCorePointerFromSolutionEnum.cpp\
+					./cores/CorePointerFromSolutionEnum.cpp\
+					./cores/ad_core.cpp\
+					./main/EnvironmentInit.cpp\
+					./main/EnvironmentFinalize.cpp\
+					./analyses/EnumToAnalysis.h\
+					./analyses/EnumToAnalysis.cpp\
+					./analyses/Analysis.h\
 					./solutionsequences/solutionsequence_linear.cpp\
 					./solutionsequences/solutionsequence_nonlinear.cpp\
@@ -370,49 +360,42 @@
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
-					  ./analyses/dakota_core.cpp\
-					  ./analyses/DakotaSpawnCore.h\
-					  ./analyses/DakotaSpawnCore.cpp
+					  ./modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp\
+					  ./cores/dakota_core.cpp\
+					  ./cores/DakotaSpawnCore.h\
+					  ./cores/DakotaSpawnCore.cpp
 #}}}
 #Transient sources  {{{
 transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
-							./analyses/transient_core.cpp
+							./cores/transient_core.cpp
 #}}}
 #Steadystate sources  {{{
-steadystate_sources = ./analyses/steadystate_core.cpp
+steadystate_sources = ./cores/steadystate_core.cpp
 #}}}
 #Masstransport sources  {{{
-masstransport_sources = ./modules/ModelProcessorx/Masstransport/UpdateElementsMasstransport.cpp\
-								./modules/ModelProcessorx/Masstransport/CreateNodesMasstransport.cpp\
-								./modules/ModelProcessorx/Masstransport/CreateConstraintsMasstransport.cpp\
-								./modules/ModelProcessorx/Masstransport/CreateLoadsMasstransport.cpp\
-								./modules/ModelProcessorx/FreeSurfaceTop/UpdateElementsFreeSurfaceTop.cpp\
-								./modules/ModelProcessorx/FreeSurfaceTop/CreateNodesFreeSurfaceTop.cpp\
-								./modules/ModelProcessorx/FreeSurfaceTop/CreateConstraintsFreeSurfaceTop.cpp\
-								./modules/ModelProcessorx/FreeSurfaceTop/CreateLoadsFreeSurfaceTop.cpp\
-								./modules/ModelProcessorx/FreeSurfaceBase/UpdateElementsFreeSurfaceBase.cpp\
-								./modules/ModelProcessorx/FreeSurfaceBase/CreateNodesFreeSurfaceBase.cpp\
-								./modules/ModelProcessorx/FreeSurfaceBase/CreateConstraintsFreeSurfaceBase.cpp\
-								./modules/ModelProcessorx/FreeSurfaceBase/CreateLoadsFreeSurfaceBase.cpp\
-								./analyses/masstransport_core.cpp
+masstransport_sources = ./analyses/ExtrudeFromBaseAnalysis.h\
+								./analyses/ExtrudeFromBaseAnalysis.cpp\
+								./analyses/ExtrudeFromTopAnalysis.h\
+								./analyses/ExtrudeFromTopAnalysis.cpp\
+								./analyses/MasstransportAnalysis.h\
+								./analyses/MasstransportAnalysis.cpp\
+								./analyses/FreeSurfaceBaseAnalysis.h\
+								./analyses/FreeSurfaceBaseAnalysis.cpp\
+								./analyses/FreeSurfaceTopAnalysis.h\
+								./analyses/FreeSurfaceTopAnalysis.cpp\
+								./cores/masstransport_core.cpp\
+								./cores/extrudefrombase_core.cpp\
+								./cores/extrudefromtop_core.cpp
 
 #}}}
 #Thermal sources  {{{
-thermal_sources = ./modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp\
-					   ./modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp\
-					   ./modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp\
-					   ./modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp\
-					   ./modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp\
-					   ./modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp\
-					   ./modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp\
-					   ./modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp\
-					   ./modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp\
-					   ./modules/ModelProcessorx/Melting/CreateNodesMelting.cpp\
-					   ./modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp\
-					   ./modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp\
-					   ./modules/ConstraintsStatex/ThermalConstraintsState.cpp\
-					   ./modules/ConstraintsStatex/ThermalIsPresent.cpp\
-					   ./modules/ResetConstraintsx/ThermalConstraintsReset.cpp \
-					   ./analyses/thermal_core.cpp\
-					   ./analyses/enthalpy_core.cpp\
+thermal_sources = ./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h\
+					   ./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp\
+						./analyses/ThermalAnalysis.h\
+						./analyses/ThermalAnalysis.cpp\
+						./analyses/EnthalpyAnalysis.h\
+						./analyses/EnthalpyAnalysis.cpp\
+						./analyses/MeltingAnalysis.h\
+						./analyses/MeltingAnalysis.cpp\
+					   ./cores/thermal_core.cpp\
 					   ./solutionsequences/solutionsequence_thermal_nonlinear.cpp
 #}}}
@@ -460,80 +443,68 @@
 					  ./shared/Numerics/BrentSearch.cpp\
 					  ./shared/Numerics/OptimalSearch.cpp \
-					  ./analyses/control_core.cpp\
-					  ./analyses/controltao_core.cpp\
-					  ./analyses/objectivefunction.cpp\
-					  ./analyses/gradient_core.cpp\
-					  ./analyses/adjointstressbalance_core.cpp\
-					  ./analyses/adjointbalancethickness_core.cpp\
-					  ./analyses/AdjointCorePointerFromSolutionEnum.cpp\
+					  ./cores/control_core.cpp\
+					  ./cores/controltao_core.cpp\
+					  ./cores/objectivefunction.cpp\
+					  ./cores/gradient_core.cpp\
+					  ./cores/adjointstressbalance_core.cpp\
+					  ./cores/adjointbalancethickness_core.cpp\
+					  ./cores/AdjointCorePointerFromSolutionEnum.cpp\
+					  ./analyses/AdjointBalancethicknessAnalysis.h\
+					  ./analyses/AdjointBalancethicknessAnalysis.cpp\
+					  ./analyses/AdjointHorizAnalysis.h\
+					  ./analyses/AdjointHorizAnalysis.cpp\
 					  ./solutionsequences/solutionsequence_adjoint_linear.cpp
 
 #}}}
 #Hydrology sources  {{{
-hydrology_sources  = ./modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp\
-					      ./modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp\
-					      ./modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp\
-					      ./modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp \
-							./modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp \
-							./modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp \
-							./modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp \
-							./modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp\
-							./modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp \
-							./modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp \
-							./analyses/hydrology_core.cpp\
+hydrology_sources  = ./analyses/HydrologyDCEfficientAnalysis.h\
+							./analyses/HydrologyDCEfficientAnalysis.cpp\
+							./analyses/HydrologyDCInefficientAnalysis.h\
+							./analyses/HydrologyDCInefficientAnalysis.cpp\
+							./analyses/HydrologyShreveAnalysis.h\
+							./analyses/HydrologyShreveAnalysis.cpp\
+							./cores/hydrology_core.cpp\
 							./solutionsequences/solutionsequence_hydro_nonlinear.cpp
 #}}}
 #Stressbalance sources  {{{
-stressbalance_sources = ./modules/ModelProcessorx/Stressbalance/UpdateElementsStressbalance.cpp\
-					      ./modules/ModelProcessorx/Stressbalance/CreateNodesStressbalance.cpp \
-					      ./modules/ModelProcessorx/Stressbalance/CreateConstraintsStressbalance.cpp \
-					      ./modules/ModelProcessorx/Stressbalance/CreateLoadsStressbalance.cpp\
-					      ./modules/ModelProcessorx/StressbalanceVertical/UpdateElementsStressbalanceVertical.cpp\
-					      ./modules/ModelProcessorx/StressbalanceVertical/CreateNodesStressbalanceVertical.cpp \
-					      ./modules/ModelProcessorx/StressbalanceVertical/CreateConstraintsStressbalanceVertical.cpp \
-					      ./modules/ModelProcessorx/StressbalanceVertical/CreateLoadsStressbalanceVertical.cpp\
-					      ./modules/ModelProcessorx/StressbalanceSIA/UpdateElementsStressbalanceSIA.cpp\
-					      ./modules/ModelProcessorx/StressbalanceSIA/CreateNodesStressbalanceSIA.cpp \
-					      ./modules/ModelProcessorx/StressbalanceSIA/CreateConstraintsStressbalanceSIA.cpp \
-							./modules/ModelProcessorx/StressbalanceSIA/CreateLoadsStressbalanceSIA.cpp \
-							./analyses/stressbalance_core.cpp\
+stressbalance_sources = ./analyses/StressbalanceAnalysis.h\
+							./analyses/StressbalanceAnalysis.cpp\
+							./analyses/StressbalanceSIAAnalysis.h\
+							./analyses/StressbalanceSIAAnalysis.cpp\
+							./analyses/StressbalanceVerticalAnalysis.h\
+							./analyses/StressbalanceVerticalAnalysis.cpp\
+							./cores/stressbalance_core.cpp\
 							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
 #}}}
 #Balanced sources  {{{
-balanced_sources = ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp\
-					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
-					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
-						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
-						 ./modules/ModelProcessorx/Balancevelocity/UpdateElementsBalancevelocity.cpp\
-						 ./modules/ModelProcessorx/Balancevelocity/CreateNodesBalancevelocity.cpp\
-						 ./modules/ModelProcessorx/Balancevelocity/CreateConstraintsBalancevelocity.cpp\
-						 ./modules/ModelProcessorx/Balancevelocity/CreateLoadsBalancevelocity.cpp\
-						 ./analyses/balancethickness_core.cpp \
-						 ./analyses/balancevelocity_core.cpp \
-						 ./analyses/dummy_core.cpp
+balanced_sources = ./analyses/BalancevelocityAnalysis.h\
+						 ./analyses/BalancevelocityAnalysis.cpp\
+						 ./analyses/SmoothedSurfaceSlopeXAnalysis.h\
+						 ./analyses/SmoothedSurfaceSlopeXAnalysis.cpp\
+						 ./analyses/SmoothedSurfaceSlopeYAnalysis.h\
+						 ./analyses/SmoothedSurfaceSlopeYAnalysis.cpp\
+						 ./analyses/BalancethicknessAnalysis.h\
+						 ./analyses/BalancethicknessAnalysis.cpp\
+						 ./analyses/BalancethicknessSoftAnalysis.h\
+						 ./analyses/BalancethicknessSoftAnalysis.cpp\
+						 ./cores/balancethickness_core.cpp \
+						 ./cores/balancevelocity_core.cpp \
+						 ./cores/dummy_core.cpp
 #}}}
 #Slope sources  {{{
-slope_sources =  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp\
-					  ./modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp \
-					  ./modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp\
-					  ./modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp\
-					  ./modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp\
-					  ./modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp \
-					  ./modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp\
-					  ./modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp\
-					  ./analyses/surfaceslope_core.cpp\
-					  ./analyses/bedslope_core.cpp
+slope_sources =  ./analyses/L2ProjectionBaseAnalysis.h\
+					  ./analyses/L2ProjectionBaseAnalysis.cpp\
+					  ./cores/surfaceslope_core.cpp\
+					  ./cores/bedslope_core.cpp
+#}}}
+#MeshDeformation sources  {{{
+meshdeformation_sources = ./analyses/MeshdeformationAnalysis.h\
+					  ./analyses/MeshdeformationAnalysis.cpp\
+					  ./cores/meshdeformation_core.cpp
 #}}}
 #Gia sources  {{{
-gia_sources =  ./analyses/gia_core.cpp\
-					./modules/ModelProcessorx/Gia/UpdateElementsGia.cpp\
-					./modules/ModelProcessorx/Gia/CreateNodesGia.cpp \
-					./modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp\
-					./modules/ModelProcessorx/Gia/CreateLoadsGia.cpp\
+gia_sources =  ./cores/gia_core.cpp\
+					./analyses/GiaAnalysis.h\
+					./analyses/GiaAnalysis.cpp\
 					./modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp\
 					./modules/GiaDeflectionCorex/GiaDeflectionCorex.h\
@@ -548,4 +519,11 @@
 
 #}}}
+#Damage sources  {{{
+damage_sources =  ./cores/damage_core.cpp\
+						./analyses/DamageEvolutionAnalysis.h\
+						./analyses/DamageEvolutionAnalysis.cpp\
+						./solutionsequences/solutionsequence_damage_nonlinear.cpp
+
+#}}}
 #Groundingline sources  {{{
 groundingline_sources= ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
@@ -557,4 +535,10 @@
 				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
 #}}}
+#Responses sources  {{{
+responses_sources= ./classes/Massfluxatgate.h \
+				   ./modules/ModelProcessorx/CreateOutputDefinitions.cpp\
+				   ./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h\
+				   ./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp
+#}}}
 #Android sources  {{{
 android_sources = 
@@ -563,6 +547,4 @@
 threed_sources = ./classes/gauss/GaussPenta.h\
 				     ./classes/gauss/GaussPenta.cpp\
-				     ./classes/ElementResults/PentaP1ElementResult.h\
-				     ./classes/ElementResults/PentaP1ElementResult.cpp\
 				     ./classes/Inputs/PentaInput.h\
 				     ./classes/Inputs/PentaInput.cpp\
@@ -683,6 +665,4 @@
 			     ./modules/Kml2Expx/Kml2Expx.h\
 			     ./modules/Kml2Expx/Kml2Expx.cpp\
-			     ./modules/Shp2Expx/Shp2Expx.h\
-			     ./modules/Shp2Expx/Shp2Expx.cpp\
 			     ./modules/Shp2Kmlx/Shp2Kmlx.h\
 			     ./modules/Shp2Kmlx/Shp2Kmlx.cpp\
@@ -762,7 +742,4 @@
 					./toolkits/petsc/patches/NewMat.cpp\
 					./toolkits/petsc/patches/VecFree.cpp\
-					./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp\
-					./toolkits/petsc/patches/PetscVectorToDoubleVector.cpp\
-					./toolkits/petsc/patches/VecDuplicatePatch.cpp\
 					./toolkits/petsc/patches/KSPFree.cpp\
 					./toolkits/petsc/patches/MatFree.cpp\
@@ -784,5 +761,5 @@
 mumps_sources=      ./toolkits/mumps\
 					./toolkits/mumps/mumpsincludes.h\
-					./toolkits/mumps/MpiDenseMumpsSolve.cpp
+					./toolkits/mumps/MumpsSolve.cpp
 #}}}
 #Gsl sources  {{{
@@ -811,9 +788,4 @@
 			./shared/TriMesh/SplitMeshForRifts.cpp\
 			./shared/TriMesh/TriMeshUtils.cpp\
-			./modules/Chacox/Chacox.h\
-			./modules/Chacox/Chacox.cpp\
-			./modules/Chacox/input_parse.cpp\
-			./modules/Chacox/chaco_seconds.cpp\
-			./modules/Chacox/user_params.cpp\
 			./modules/TriaSearchx/TriaSearchx.h\
 			./modules/TriaSearchx/TriaSearchx.cpp\
@@ -855,8 +827,17 @@
 			./modules/ElementConnectivityx/ElementConnectivityx.cpp\
 			./modules/ElementConnectivityx/ElementConnectivityx.h\
-			./modules/Scotchx/Scotchx.cpp\
-			./modules/Scotchx/Scotchx.h\
 			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp\
 			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
+if CHACO
+modules_sources+= ./modules/Chacox/Chacox.h\
+						./modules/Chacox/Chacox.cpp\
+						./modules/Chacox/input_parse.cpp\
+						./modules/Chacox/chaco_seconds.cpp\
+						./modules/Chacox/user_params.cpp
+endif
+if SCOTCH
+modules_sources+= ./modules/Scotchx/Scotchx.cpp\
+						./modules/Scotchx/Scotchx.h
+endif
 #}}}
 
@@ -925,4 +906,8 @@
 endif
 
+if MESHDEFORMATION
+issm_sources  +=  $(meshdeformation_sources)
+endif
+
 if GROUNDINGLINE
 issm_sources +=  $(groundingline_sources)
@@ -933,4 +918,8 @@
 endif
 
+if RESPONSES
+issm_sources +=  $(responses_sources)
+endif
+
 if ANDROID
 issm_sources +=  $(android_sources)
@@ -951,4 +940,8 @@
 if KRIGING
 issm_sources +=  $(pkriging_sources)
+endif
+
+if DAMAGE
+issm_sources +=  $(damage_sources)
 endif
 #}}}
@@ -992,6 +985,5 @@
 #}}}
 #Overload library, to overload any non-standard symbols. {{{
-libISSMOverload_a_SOURCES = ./shared/String/stricmp.cpp\
-							./shared/String/ApiPrintf.cpp
+libISSMOverload_a_SOURCES = ./shared/String/ApiPrintf.cpp
 
 libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
@@ -1013,5 +1005,5 @@
 
 #External packages
-LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(METEOIOLIB) $(SNOWPACKLIB)
+LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
 
 if FORTRAN
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 16560)
@@ -0,0 +1,25 @@
+#include "./AdjointBalancethicknessAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processor*/
+int  AdjointBalancethicknessAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file AdjointBalancethicknessAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AdjointBalancethicknessAnalysis_
+#define _AdjointBalancethicknessAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AdjointBalancethicknessAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: sm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp	(revision 16559)
+++ 	(revision )
@@ -1,46 +1,0 @@
-/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
- * \brief: return type of analyses, number of analyses and core solution function.
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype){
-
-	/*output: */
-	void (*adjointcore)(FemModel*)=NULL;
-
-	switch(solutiontype){
-
-		case StressbalanceSolutionEnum:
-			adjointcore=&adjointstressbalance_core;
-			break;
-		case SteadystateSolutionEnum:
-			adjointcore=&adjointstressbalance_core;
-			break;
-		case BalancethicknessSolutionEnum:
-			adjointcore=&adjointbalancethickness_core;
-			break;
-		case BalancethicknessSoftSolutionEnum:
-			adjointcore=&dummy_core;
-			break;
-		default:
-			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
-			break;
-	}
-
-	/*Assign output pointer:*/
-	_assert_(padjointcore);
-	*padjointcore=adjointcore;
-
-}
Index: /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 16560)
@@ -0,0 +1,25 @@
+#include "./AdjointHorizAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  AdjointHorizAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void AdjointHorizAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file AdjointHorizAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AdjointHorizAnalysis_
+#define _AdjointHorizAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AdjointHorizAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/Analysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/Analysis.h	(revision 16560)
@@ -0,0 +1,27 @@
+/*!\file:  Analysis.h
+ * \brief abstract class for Analysis objects
+ */ 
+
+#ifndef _ANALYSIS_H_
+#define _ANALYSIS_H_
+
+class Parameters;
+class IoModel;
+class Elements;
+class Nodes;
+class Constraints;
+class Loads;
+
+class Analysis{
+
+	public: 
+
+		virtual      ~Analysis(){};
+		virtual int  DofsPerNode(int** doflist,int meshtype,int approximation)=0;
+		virtual void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum)=0;
+		virtual void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void CreateNodes(Nodes* nodes,IoModel* iomodel)=0;
+		virtual void CreateConstraints(Constraints* constraints,IoModel* iomodel)=0;
+		virtual void CreateLoads(Loads* loads, IoModel* iomodel)=0;
+};
+#endif
Index: sm/trunk/src/c/analyses/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp	(revision 16559)
+++ 	(revision )
@@ -1,141 +1,0 @@
-/*!\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 "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
-
-	/*output: */
-	int  numanalyses;
-	int* analyses=NULL;
-
-	/*Analyses lists*/
-	switch(solutiontype){
-
-		case StressbalanceSolutionEnum:
-			numanalyses=5;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=StressbalanceAnalysisEnum;
-			analyses[1]=StressbalanceVerticalAnalysisEnum;
-			analyses[2]=StressbalanceSIAAnalysisEnum;
-			analyses[3]=SurfaceSlopeAnalysisEnum;
-			analyses[4]=BedSlopeAnalysisEnum;
-			break;
-
-		case SteadystateSolutionEnum:
-			numanalyses=8;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=StressbalanceAnalysisEnum;
-			analyses[1]=StressbalanceVerticalAnalysisEnum;
-			analyses[2]=StressbalanceSIAAnalysisEnum;
-			analyses[3]=SurfaceSlopeAnalysisEnum;
-			analyses[4]=BedSlopeAnalysisEnum;
-			analyses[5]=EnthalpyAnalysisEnum;
-			analyses[6]=ThermalAnalysisEnum;
-			analyses[7]=MeltingAnalysisEnum;
-			break;
-
-		case ThermalSolutionEnum:
-			numanalyses=2;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=ThermalAnalysisEnum;
-			analyses[1]=MeltingAnalysisEnum;
-			break;
-
-		case EnthalpySolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=EnthalpyAnalysisEnum;
-			break;
-
-		case HydrologySolutionEnum:
-			numanalyses=5;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=HydrologyShreveAnalysisEnum;
-			analyses[1]=HydrologyDCInefficientAnalysisEnum;
-			analyses[2]=HydrologyDCEfficientAnalysisEnum;
-			analyses[3]=SurfaceSlopeAnalysisEnum;
-			analyses[4]=BedSlopeAnalysisEnum;
-			break;
-
-		case MasstransportSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=MasstransportAnalysisEnum;
-			break;
-
-		case BalancethicknessSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancethicknessAnalysisEnum;
-			break;
-
-		case BalancethicknessSoftSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancethicknessAnalysisEnum;
-			break;
-
-		case BalancevelocitySolutionEnum:
-			numanalyses=2;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancevelocityAnalysisEnum;
-			analyses[1]=SurfaceSlopeAnalysisEnum;
-			break;
-
-		case SurfaceSlopeSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=SurfaceSlopeAnalysisEnum;
-			break;
-
-		case BedSlopeSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BedSlopeAnalysisEnum;
-			break;
-
-		case GiaSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=GiaAnalysisEnum;
-			break;
-
-		case TransientSolutionEnum:
-			numanalyses=11;
-			analyses=xNew<int>(numanalyses);
-			analyses[ 0]=StressbalanceAnalysisEnum;
-			analyses[ 1]=StressbalanceVerticalAnalysisEnum;
-			analyses[ 2]=StressbalanceSIAAnalysisEnum;
-			analyses[ 3]=SurfaceSlopeAnalysisEnum;
-			analyses[ 4]=BedSlopeAnalysisEnum;
-			analyses[ 5]=ThermalAnalysisEnum;
-			analyses[ 6]=MeltingAnalysisEnum;
-			analyses[ 7]=EnthalpyAnalysisEnum;
-			analyses[ 8]=MasstransportAnalysisEnum;
-			analyses[ 9]=FreeSurfaceBaseAnalysisEnum;
-			analyses[10]=FreeSurfaceTopAnalysisEnum;
-			break;
-
-		default:
-			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
-			break;
-	}
-
-	/*Assign output pointers:*/
-	if(pnumanalyses) *pnumanalyses=numanalyses;
-	if(panalyses)    *panalyses=analyses;
-	else              xDelete<int>(analyses);
-}
Index: /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 16560)
@@ -0,0 +1,113 @@
+#include "./BalancethicknessAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancethicknessAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void BalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void BalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int    stabilization,finiteelement;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+}/*}}}*/
+void BalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int  stabilization;
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->meshtype==Mesh3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void BalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int    stabilization;	
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Do not add constraints in DG*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum,P1Enum);
+	}
+
+}/*}}}*/
+void BalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int element;
+	int stabilization;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,BalancethicknessAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file BalancethicknessAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancethicknessAnalysis_
+#define _BalancethicknessAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancethicknessAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 16560)
@@ -0,0 +1,25 @@
+#include "./BalancethicknessSoftAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancethicknessSoftAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file BalancethicknessSoftAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancethicknessSoftAnalysis_
+#define _BalancethicknessSoftAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancethicknessSoftAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 16560)
@@ -0,0 +1,58 @@
+#include "./BalancevelocityAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancevelocityAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void BalancevelocityAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void BalancevelocityAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+}/*}}}*/
+void BalancevelocityAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Check in 3d*/
+	if(iomodel->meshtype==Mesh3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	::CreateNodes(nodes,iomodel,BalancevelocityAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}/*}}}*/
+void BalancevelocityAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints for now*/
+	//IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancevelocityAnalysisEnum,P1Enum);
+}/*}}}*/
+void BalancevelocityAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file BalancevelocityAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancevelocityAnalysis_
+#define _BalancevelocityAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancevelocityAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: sm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp	(revision 16559)
+++ 	(revision )
@@ -1,127 +1,0 @@
-/*!\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 "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype){
-
-	/*output: */
-	void (*solutioncore)(FemModel*)=NULL;
-
-	switch(solutiontype){
-
-		case StressbalanceSolutionEnum:
-			#ifdef _HAVE_STRESSBALANCE_
-			solutioncore=&stressbalance_core;
-			#else
-			_error_("ISSM was not compiled with stressbalance 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 BalancethicknessSoftSolutionEnum:
-			#ifdef _HAVE_BALANCED_
-			solutioncore=&dummy_core;
-			#else
-			_error_("ISSM was not compiled with balanced capabilities. Exiting");
-			#endif
-			break;
-		case BalancevelocitySolutionEnum:
-			#ifdef _HAVE_BALANCED_
-			solutioncore=&balancevelocity_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 MasstransportSolutionEnum:
-			#ifdef _HAVE_MASSTRANSPORT_
-			solutioncore=&masstransport_core;
-			#else
-			_error_("ISSM was not compiled with masstransport capabilities. Exiting");
-			#endif
-			break;
-
-		case GiaSolutionEnum:
-			#ifdef _HAVE_GIA_
-			solutioncore=&gia_core;
-			#else
-			_error_("ISSM was not compiled with gia capabilities. Exiting");
-			#endif
-			break;
-
-		default:
-			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
-			break;
-	}
-
-	/*Assign output pointer:*/
-	_assert_(psolutioncore);
-	*psolutioncore=solutioncore;
-
-}
Index: sm/trunk/src/c/analyses/DakotaSpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp	(revision 16559)
+++ 	(revision )
@@ -1,188 +1,0 @@
-/*!\file:  DakotaSpawnCore.cpp
-
- * \brief: run core ISSM solution using Dakota inputs coming from CPU 0.
- * \sa qmu.cpp DakotaPlugin.cpp
- *
- * This routine needs to be understood simultaneously with qmu.cpp and DakotaPlugin. 
- * DakotaSpawnCoreParallel is called by all CPUS, with CPU 0 holding Dakota variable values, along 
- * with variable descriptors. 
- *
- * DakotaSpawnCoreParallel takes care of broadcasting the variables and their descriptors across the MPI 
- * ring. Once this is done, we use the variables to modify the inputs for the solution core. 
- * For ex, if "rho_ice" is provided, for ex 920, we include "rho_ice" in the inputs, then 
- * call the core with the modified inputs. This is the way we get Dakota to explore the parameter 
- * spce of the core. 
- *
- * Once the core is called, we process the results of the core, and using the processed results, 
- * we compute response functions. The responses are computed on all CPUS, but they are targeted 
- * for CPU 0, which will get these values back to the Dakota engine. 
- *
- */ 
-
-/*Includes and prototypes: {{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./analyses.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-
-void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses);
-void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses);
-/*}}}*/
-
-/*Notice the d_, which prefixes anything that is being provided to us by the Dakota pluggin. Careful. some things are ours, some are dakotas!: */
-int DakotaSpawnCore(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, void* void_femmodel,int counter){
-
-	char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
-	int        numresponsedescriptors;
-	char      *string                   = NULL;
-	int        solution_type;
-	bool       control_analysis         = false;
-	void     (*solutioncore)(FemModel*) = NULL;
-	FemModel  *femmodel                 = NULL;
-	bool       nodakotacore             = true;
-
-	/*If counter==-1 on cpu0, it means that the dakota runs are done. In which case, bail out and return 0: */
-	ISSM_MPI_Bcast(&counter,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
-	if(counter==-1)return 0;
-
-	/*cast void_femmodel to FemModel: */
-	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
-
-	/*retrieve parameters: */
-	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
-
-	if(VerboseQmu()) _printf0_("qmu iteration: " << counter << "\n");
-
-	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
-	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
-
-	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
-	InputUpdateFromDakotax(femmodel,d_variables,d_variables_descriptors,d_numvariables);
-
-	/*Determine solution sequence: */
-	if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
-	WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
-
-	/*Run the core solution sequence: */
-	solutioncore(femmodel);
-
-	/*compute responses: */
-	if(VerboseQmu()) _printf0_("compute dakota responses:\n");
-	femmodel->DakotaResponsesx(d_responses,responses_descriptors,numresponsedescriptors,d_numresponses);
-
-	/*Free ressources:*/
-	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
-
-	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
-}
-
-void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){ /*{{{*/
-
-	/* * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
-	 * from cpu 0 to all other cpus.
-	 */ 
-
-	int i;
-	int my_rank;
-
-	/*inputs and outputs: */
-	double* variables=NULL;
-	char**  variables_descriptors=NULL;
-	int     numvariables;
-	int     numresponses;
-
-	/*intermediary: */
-	char* string=NULL;
-	int   string_length;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	/*recover inputs from pointers: */
-	variables=*pvariables;
-	variables_descriptors=*pvariables_descriptors;
-	numvariables=*pnumvariables;
-	numresponses=*pnumresponses;
-
-	/*numvariables: */
-	ISSM_MPI_Bcast(&numvariables,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
-
-	/*variables:*/
-	if(my_rank!=0)variables=xNew<double>(numvariables);
-	ISSM_MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
-
-	/*variables_descriptors: */
-	if(my_rank!=0){
-		variables_descriptors=xNew<char*>(numvariables);
-	}
-	for(i=0;i<numvariables;i++){
-		if(my_rank==0){
-			string=variables_descriptors[i];
-			string_length=(strlen(string)+1)*sizeof(char);
-		}
-		ISSM_MPI_Bcast(&string_length,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
-		if(my_rank!=0)string=xNew<char>(string_length);
-		ISSM_MPI_Bcast(string,string_length,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
-		if(my_rank!=0)variables_descriptors[i]=string;
-	}
-
-	/*numresponses: */
-	ISSM_MPI_Bcast(&numresponses,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
-
-	/*Assign output pointers:*/
-	*pnumvariables=numvariables;
-	*pvariables=variables;
-	*pvariables_descriptors=variables_descriptors;
-	*pnumresponses=numresponses;
-} /*}}}*/
-void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses){ /*{{{*/
-
-	/*\brief DakotaFree: free allocations on other cpus, not done by Dakota.*/
-
-	int i;
-	int my_rank;
-
-	double  *variables             = NULL;
-	char   **variables_descriptors = NULL;
-	char   **responses_descriptors = NULL;
-	char    *string                = NULL;
-
-	/*recover pointers: */
-	variables=*pvariables;
-	variables_descriptors=*pvariables_descriptors;
-	responses_descriptors=*presponses_descriptors;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	/*Free variables and variables_descriptors only on cpu !=0*/
-	if(my_rank!=0){
-		xDelete<double>(variables);
-		for(i=0;i<numvariables;i++){
-			string=variables_descriptors[i];
-			xDelete<char>(string);
-		}
-		xDelete<char*>(variables_descriptors);
-	}
-
-	//responses descriptors on every cpu
-	for(i=0;i<numresponses;i++){
-		string=responses_descriptors[i];
-		xDelete<char>(string);
-	}
-	//rest of dynamic allocations.
-	xDelete<char*>(responses_descriptors);
-
-	/*Assign output pointers:*/
-	*pvariables=variables;
-	*pvariables_descriptors=variables_descriptors;
-	*presponses_descriptors=responses_descriptors;
-} /*}}}*/
Index: sm/trunk/src/c/analyses/DakotaSpawnCore.h
===================================================================
--- /issm/trunk/src/c/analyses/DakotaSpawnCore.h	(revision 16559)
+++ 	(revision )
@@ -1,4 +1,0 @@
-#ifndef _DAKOTA_SPAWN_CORE_
-#define _DAKOTA_SPAWN_CORE_
-int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
-#endif
Index: /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 16560)
@@ -0,0 +1,94 @@
+#include "./DamageEvolutionAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  DamageEvolutionAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*retrieve some parameters: */
+	parameters->AddObject(iomodel->CopyConstantObject(DamageLawEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageStabilizationEnum));
+
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyLockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxDamageEnum));
+
+	/*Retrieve law dependent parameters: */
+	char* law  = NULL;
+	iomodel->Constant(&law,DamageLawEnum);
+	if (strcmp(law,"pralong")==0){
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC1Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC2Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC3Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC4Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageStressThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageHealingEnum));
+	}
+	xDelete<char>(law);
+
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	/*What input do I need to run my damage evolution model?*/
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	iomodel->FetchDataToInput(elements,DamageDEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(DamageDEnum, QmuDamageDEnum);
+	}
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	iomodel->FetchData(1,MeshVertexonbedEnum);
+	::CreateNodes(nodes,iomodel,DamageEvolutionAnalysisEnum,P1Enum);
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	int stabilization;
+	iomodel->Constant(&stabilization,DamageStabilizationEnum);
+
+	IoModelToConstraintsx(constraints,iomodel,DamageSpcdamageEnum,DamageEvolutionAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*create penalties for nodes: no node can have a damage > 1*/
+	iomodel->FetchData(1,DamageSpcdamageEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+			if (xIsNan<IssmDouble>(iomodel->Data(DamageSpcdamageEnum)[i])){ //No penalty applied on spc nodes!
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,DamageEvolutionAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,DamageSpcdamageEnum);
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file DamageEvolutionAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _DamageEvolutionAnalysis_
+#define _DamageEvolutionAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class DamageEvolutionAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 16560)
@@ -0,0 +1,171 @@
+#include "./EnthalpyAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  EnthalpyAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void EnthalpyAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void EnthalpyAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool dakota_analysis;
+	bool isenthalpy;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->meshtype==Mesh2DhorizontalEnum)return;
+
+	/*Is enthalpy requested?*/
+	iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+	if(!isenthalpy) return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	iomodel->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,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	iomodel->FetchDataToInput(elements,TemperatureEnum);
+	iomodel->FetchDataToInput(elements,WaterfractionEnum);
+	iomodel->FetchDataToInput(elements,EnthalpyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	InputUpdateFromConstantx(elements,0.,VxMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
+}/*}}}*/
+void EnthalpyAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,EnthalpyAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void EnthalpyAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        count;
+	int        M,N;
+	bool       spcpresent = false;
+	IssmDouble heatcapacity;
+	IssmDouble referencetemperature;
+
+	/*Output*/
+	IssmDouble *spcvector  = NULL;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+
+	/*return if 2d mesh*/
+	if(iomodel->meshtype==Mesh2DhorizontalEnum) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(&spcvector,&M,&N,ThermalSpctemperatureEnum);
+
+	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
+	/*Transient or static?:*/
+	if(M==iomodel->numberofvertices){
+		/*static: just create Constraints objects*/
+		count=0;
+
+		for(int i=0;i<iomodel->numberofvertices;i++){
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				if (!xIsNan<IssmDouble>(spcvector[i])){
+
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,heatcapacity*(spcvector[i]-referencetemperature),EnthalpyAnalysisEnum));
+					count++;
+
+				}
+			}
+		}
+	}
+	else if (M==(iomodel->numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+		count=0;
+
+		/*figure out times: */
+		times=xNew<IssmDouble>(N);
+		for(int j=0;j<N;j++){
+			times[j]=spcvector[(M-1)*N+j];
+		}
+
+		/*Create constraints from x,y,z: */
+		for(int i=0;i<iomodel->numberofvertices;i++){
+
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				/*figure out times and values: */
+				values=xNew<IssmDouble>(N);
+				spcpresent=false;
+				for(int j=0;j<N;j++){
+					values[j]=heatcapacity*(spcvector[i*N+j]-referencetemperature);
+					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+				}
+
+				if(spcpresent){
+					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,N,times,values,EnthalpyAnalysisEnum));
+					count++;
+				}
+				xDelete<IssmDouble>(values);
+			}
+		}
+	}
+	else{
+		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+	}
+
+	/*Free ressources:*/
+	iomodel->DeleteData(spcvector,ThermalSpctemperatureEnum);
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void EnthalpyAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads */
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/EnthalpyAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file EnthalpyAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _EnthalpyAnalysis_
+#define _EnthalpyAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class EnthalpyAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 16560)
@@ -0,0 +1,47 @@
+/*
+* \file EnumToAnalysis.cpp
+* \brief: output class depending on enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include "./analyses.h"
+#include "../shared/shared.h"
+
+Analysis* EnumToAnalysis(int analysis_enum){
+
+	switch(analysis_enum){
+		case AdjointBalancethicknessAnalysisEnum : return new AdjointBalancethicknessAnalysis();
+		case AdjointHorizAnalysisEnum : return new AdjointHorizAnalysis();
+		case BalancethicknessAnalysisEnum : return new BalancethicknessAnalysis();
+		case BalancethicknessSoftAnalysisEnum : return new BalancethicknessSoftAnalysis();
+		case BalancevelocityAnalysisEnum : return new BalancevelocityAnalysis();
+		case L2ProjectionBaseAnalysisEnum : return new L2ProjectionBaseAnalysis();
+		case DamageEvolutionAnalysisEnum : return new DamageEvolutionAnalysis();
+		case StressbalanceAnalysisEnum : return new StressbalanceAnalysis();
+		case StressbalanceSIAAnalysisEnum : return new StressbalanceSIAAnalysis();
+		case StressbalanceVerticalAnalysisEnum : return new StressbalanceVerticalAnalysis();
+		case EnthalpyAnalysisEnum : return new EnthalpyAnalysis();
+		case HydrologyShreveAnalysisEnum : return new HydrologyShreveAnalysis();
+		case HydrologyDCInefficientAnalysisEnum : return new HydrologyDCInefficientAnalysis();
+		case HydrologyDCEfficientAnalysisEnum : return new HydrologyDCEfficientAnalysis();
+		case MeltingAnalysisEnum : return new MeltingAnalysis();
+		case MasstransportAnalysisEnum : return new MasstransportAnalysis();
+		case FreeSurfaceBaseAnalysisEnum : return new FreeSurfaceBaseAnalysis();
+		case FreeSurfaceTopAnalysisEnum : return new FreeSurfaceTopAnalysis();
+		case ExtrudeFromBaseAnalysisEnum : return new ExtrudeFromBaseAnalysis();
+		case ExtrudeFromTopAnalysisEnum : return new ExtrudeFromTopAnalysis();
+		case ThermalAnalysisEnum : return new ThermalAnalysis();
+		#ifdef _HAVE_GIA_
+		case GiaAnalysisEnum : return new GiaAnalysis();
+		#endif
+		#ifdef _HAVE_MESHDEFORMATION_
+		case MeshdeformationAnalysisEnum : return new MeshdeformationAnalysis();
+		#endif
+		case SmoothedSurfaceSlopeXAnalysisEnum: return new SmoothedSurfaceSlopeXAnalysis();
+		case SmoothedSurfaceSlopeYAnalysisEnum: return new SmoothedSurfaceSlopeYAnalysis();
+		default : _error_("enum provided not supported ("<<EnumToStringx(analysis_enum)<<")");
+	}
+}
Index: /issm/trunk/src/c/analyses/EnumToAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/EnumToAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/EnumToAnalysis.h	(revision 16560)
@@ -0,0 +1,14 @@
+#ifndef _ENUMTOANALYSIS_
+#define _ENUMTOANALYSIS_
+
+class Analysis;
+
+Analysis* EnumToAnalysis(int analysis_enum);
+
+#endif
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
Index: sm/trunk/src/c/analyses/EnvironmentFinalize.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp	(revision 16559)
+++ 	(revision )
@@ -1,25 +1,0 @@
-/*!\file:  EnvironmentFinalize.cpp
- * \brief: finalize Petsc, MPI, you name it
- */ 
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "../toolkits/toolkits.h"
-#include "../shared/shared.h"
-
-void EnvironmentFinalize(void){
-
-	int my_rank;
-
-	/*Make sure we are all here*/
-	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD);
-
-	/*Print closing statement*/
-	ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&my_rank);
-	if(!my_rank) printf("closing MPI\n");
-
-	/*Finalize: */
-	ISSM_MPI_Finalize();
-}
Index: sm/trunk/src/c/analyses/EnvironmentInit.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentInit.cpp	(revision 16559)
+++ 	(revision )
@@ -1,35 +1,0 @@
-/*!\file:  EnvironmentInit.cpp
- * \brief: initialize Petsc, MPI, you name it
- */ 
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include <stdio.h>
-#include "../toolkits/toolkits.h"
-
-ISSM_MPI_Comm EnvironmentInit(int argc,char** argv){
-
-	/*Output*/
-	ISSM_MPI_Comm comm = 0;
-
-	/*Initialize MPI environment: */
-	#if defined(_HAVE_MPI_)
-	ISSM_MPI_Init(&argc,&argv);
-	comm = ISSM_MPI_COMM_WORLD;
-	#else
-	comm = 1; //bogus number for comm, which does not exist anyway.
-	#endif
-
-	/*Print Banner*/
-	int my_rank = 0;
-	ISSM_MPI_Comm_rank(comm,&my_rank);
-	if(!my_rank) printf("\n");
-	if(!my_rank) printf("Ice Sheet System Model (%s) version  %s\n",PACKAGE_NAME,PACKAGE_VERSION);
-	if(!my_rank) printf("(website: %s contact: %s)\n",PACKAGE_URL,PACKAGE_BUGREPORT);
-	if(!my_rank) printf("\n");
-
-	/*Return communicator*/
-	return comm;
-}
Index: /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 16560)
@@ -0,0 +1,36 @@
+#include "./ExtrudeFromBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ExtrudeFromBaseAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+	}
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromBaseAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file ExtrudeFromBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _ExtrudeFromBaseAnalysis_
+#define _ExtrudeFromBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ExtrudeFromBaseAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 16560)
@@ -0,0 +1,36 @@
+#include "./ExtrudeFromTopAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ExtrudeFromTopAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ExtrudeFromTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+	}
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromBaseAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file ExtrudeFromTopAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _ExtrudeFromTopAnalysis_
+#define _ExtrudeFromTopAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ExtrudeFromTopAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 16560)
@@ -0,0 +1,89 @@
+#include "./FreeSurfaceBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  FreeSurfaceBaseAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->meshtype==Mesh2DhorizontalEnum)return;
+
+	/*Finite element type*/
+	int finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum,0.);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,VzEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype!=Mesh2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbed=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(!(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceBaseAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file FreeSurfaceBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _FreeSurfaceBaseAnalysis_
+#define _FreeSurfaceBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class FreeSurfaceBaseAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 16560)
@@ -0,0 +1,87 @@
+#include "./FreeSurfaceTopAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  FreeSurfaceTopAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void FreeSurfaceTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void FreeSurfaceTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->meshtype==Mesh2DhorizontalEnum)return;
+
+	int finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum,0.);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,VzEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype!=Mesh2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceTopAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonsurface=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	iomodel->FetchData(&nodeonsurface,NULL,NULL,MeshVertexonsurfaceEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(!(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceTopAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonsurface,MeshVertexonsurfaceEnum);
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file FreeSurfaceTopAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _FreeSurfaceTopAnalysis_
+#define _FreeSurfaceTopAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class FreeSurfaceTopAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/GiaAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 16560)
@@ -0,0 +1,37 @@
+#include "./GiaAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  GiaAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void GiaAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void GiaAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GiaMantleViscosityEnum);
+	iomodel->FetchDataToInput(elements,GiaLithosphereThicknessEnum);
+}/*}}}*/
+void GiaAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	::CreateNodes(nodes,iomodel,GiaAnalysisEnum,P1Enum);
+}/*}}}*/
+void GiaAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/*No constraints*/
+}/*}}}*/
+void GiaAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/GiaAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file GiaAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _GiaAnalysis_
+#define _GiaAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class GiaAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 16560)
@@ -0,0 +1,104 @@
+#include "./HydrologyDCEfficientAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyDCEfficientAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int         hydrology_model;
+	bool        isefficientlayer;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Nothing for now*/
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+
+	/*Now, do we really want DC?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,EplHeadEnum);
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Now, do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	::CreateNodes(nodes,iomodel,HydrologyDCEfficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Nothing for now*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file HydrologyDCEfficientAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyDCEfficientAnalysis_
+#define _HydrologyDCEfficientAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class HydrologyDCEfficientAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 16560)
@@ -0,0 +1,133 @@
+#include "./HydrologyDCInefficientAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyDCInefficientAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int         hydrology_model;
+	int         sedimentlimit_flag;
+	int         transfer_flag;
+	bool        isefficientlayer;
+	IssmDouble  sedimentlimit;
+	IssmDouble  penalty_factor;
+	IssmDouble  leakagefactor;
+	IssmDouble  rel_tol;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	iomodel->FetchData(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	iomodel->FetchData(&sedimentlimit_flag,HydrologydcSedimentlimitFlagEnum);
+	iomodel->FetchData(&transfer_flag,HydrologydcTransferFlagEnum);
+	iomodel->FetchData(&penalty_factor,HydrologydcPenaltyFactorEnum);
+	iomodel->FetchData(&rel_tol,HydrologydcRelTolEnum);
+
+	if(sedimentlimit_flag==1){
+		iomodel->FetchData(&sedimentlimit,HydrologydcSedimentlimitEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcSedimentlimitEnum,sedimentlimit));
+	}
+
+	if(transfer_flag==1){
+		iomodel->FetchData(&leakagefactor,HydrologydcLeakageFactorEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcLeakageFactorEnum,leakagefactor));
+	}
+
+	parameters->AddObject(new DoubleParam(HydrologydcPenaltyFactorEnum,penalty_factor));
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(new BoolParam(HydrologydcIsefficientlayerEnum,isefficientlayer));
+	parameters->AddObject(new IntParam(HydrologydcSedimentlimitFlagEnum,sedimentlimit_flag));
+	parameters->AddObject(new IntParam(HydrologydcTransferFlagEnum,transfer_flag));
+	parameters->AddObject(new DoubleParam(HydrologydcRelTolEnum,rel_tol));
+
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
+	if(isefficientlayer)iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveEnum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyDCInefficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*retrieve some parameters: */
+	int hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpcsedimentHeadEnum,HydrologyDCInefficientAnalysisEnum,P1Enum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	iomodel->FetchData(1,MeshVertexonbedEnum);
+
+	//create penalties for nodes: no node can have a temperature over the melting point
+	CreateSingleNodeToElementConnectivity(iomodel);
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if (iomodel->meshtype==Mesh3DEnum){
+			/*keep only this partition's nodes:*/
+			if(iomodel->my_vertices[i]){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}
+		}
+		else if(reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
+			if(iomodel->my_vertices[i]){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}	
+		}
+	}
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file HydrologyDCInefficientAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyDCInefficientAnalysis_
+#define _HydrologyDCInefficientAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class HydrologyDCInefficientAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 16560)
@@ -0,0 +1,81 @@
+#include "./HydrologyShreveAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyShreveAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyShreveAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*retrieve some parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(iomodel->CopyConstantObject(HydrologyshreveStabilizationEnum));
+
+}/*}}}*/
+void HydrologyShreveAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Fetch data needed: */
+	int    hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+
+	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyShreveAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*retrieve some parameters: */
+	int          hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file HydrologyShreveAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyShreveAnalysis_
+#define _HydrologyShreveAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class HydrologyShreveAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 16560)
@@ -0,0 +1,54 @@
+#include "./L2ProjectionBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  L2ProjectionBaseAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void L2ProjectionBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+	}
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	}
+	else if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchData(1,MeshVertexonbedEnum);
+	}
+	::CreateNodes(nodes,iomodel,L2ProjectionBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file L2ProjectionBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _L2ProjectionBaseAnalysis_
+#define _L2ProjectionBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class L2ProjectionBaseAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 16560)
@@ -0,0 +1,197 @@
+#include "./MasstransportAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MasstransportAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void MasstransportAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+
+}/*}}}*/
+void MasstransportAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int    stabilization,finiteelement;
+	bool   dakota_analysis;
+	bool   issmbgradients;
+	bool   ispdd;
+	bool   isdelta18o;
+	bool   isgroundingline;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
+	iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	iomodel->Constant(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
+	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum,0.);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	if(stabilization==3){
+		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for DG, we need the spc in the element
+	}
+
+	if(dakota_analysis){
+		elements->InputDuplicate(BedEnum,QmuBedEnum);
+		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
+		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
+		elements->InputDuplicate(MaskIceLevelsetEnum,QmuMaskIceLevelsetEnum);
+		if(isgroundingline) elements->InputDuplicate(MaskGroundediceLevelsetEnum,QmuMaskGroundediceLevelsetEnum);
+	}
+
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+
+	if(issmbgradients){
+		iomodel->FetchDataToInput(elements,SurfaceforcingsHrefEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsBPosEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsBNegEnum);
+	}
+	if(ispdd){
+		iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
+		if(isdelta18o){
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesLgmEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesPresentdayEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsPresentdayEnum);
+		}
+		else{
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
+		}
+	}
+	if(~ispdd && ~issmbgradients){
+		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum,0.);
+	}
+}/*}}}*/
+void MasstransportAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->meshtype==Mesh3DEnum) _error_("DG 3d not implemented yet");
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	if(iomodel->meshtype!=Mesh2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void MasstransportAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Do not add constraints in DG, they are weakly imposed*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,MasstransportSpcthicknessEnum,MasstransportAnalysisEnum,P1Enum);
+	}
+}/*}}}*/
+void MasstransportAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int stabilization;
+	int numvertex_pairing;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,MasstransportAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbed=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(!(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							MasstransportAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/MasstransportAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file MasstransportAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MasstransportAnalysis_
+#define _MasstransportAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MasstransportAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/MeltingAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 16560)
@@ -0,0 +1,71 @@
+#include "./MeltingAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MeltingAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void MeltingAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void MeltingAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->meshtype==Mesh2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	/*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,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+}/*}}}*/
+void MeltingAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,MeltingAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void MeltingAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/*No Constraints*/
+}/*}}}*/
+void MeltingAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*if 2d: Error*/
+	if(iomodel->meshtype==Mesh2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+	//create penalties for nodes: no node can have a temperature over the melting point
+	iomodel->FetchData(1,MeshVertexonbedEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+			if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,MeltingAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/MeltingAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file MeltingAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MeltingAnalysis_
+#define _MeltingAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MeltingAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 16560)
@@ -0,0 +1,25 @@
+#include "./MeshdeformationAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MeshdeformationAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file MeshdeformationAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MeshdeformationAnalysis_
+#define _MeshdeformationAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MeshdeformationAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: sm/trunk/src/c/analyses/ProcessArguments.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ProcessArguments.cpp	(revision 16559)
+++ 	(revision )
@@ -1,57 +1,0 @@
-/*!\file:  ProcessArguments.cpp
- * \brief: process arguments
- */ 
-
-#include <stdio.h>
-#include <cstring>
-
-#include "../shared/shared.h"
-
-void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ptoolkitsfilename,char** plockfilename,char** prootpath, int argc,char **argv){
-
-	char *modelname      = NULL;
-	char *binfilename    = NULL;
-	char *outbinfilename = NULL;
-	char *toolkitsfilename  = NULL;
-	char *lockfilename   = NULL;
-	char *rootpath       = NULL;
-	char *rootpatharg    = NULL;
-
-	/*Check input arguments*/
-	if(argc<2)_error_("Usage error: no solution requested");
-	if(argc<3)_error_("Usage error: missing execution directory");
-	if(argc<4)_error_("Usage error: missing model name");
-
-	/*Get requested solution*/
-	*solution_type=StringToEnumx(argv[1]);
-
-	rootpatharg=argv[2];
-	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
-		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
-	}
-	else{
-		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
-	}
-
-	modelname=argv[3];
-	if(strstr(modelname,rootpath)==NULL){
-		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
-		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
-		toolkitsfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s%s",rootpath,modelname,".toolkits");
-		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
-	}
-	else{
-		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
-		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
-		toolkitsfilename  = xNew<char>(strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s",modelname,".toolkits");
-		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
-	}
-
-	/*Clean up and assign output pointer*/
-	*pbinfilename=binfilename;
-	*poutbinfilename=outbinfilename;
-	*ptoolkitsfilename=toolkitsfilename;
-	*plockfilename=lockfilename;
-	*prootpath=rootpath;
-
-}
Index: sm/trunk/src/c/analyses/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp	(revision 16559)
+++ 	(revision )
@@ -1,31 +1,0 @@
-/*!\file: ResetBoundaryConditions.cpp
- * \brief: change boundary conditions of a model, using a solution vector from another analysis
- */ 
-
-#include "../classes/classes.h"
-#include "../modules/modules.h"
-#include "../shared/io/io.h"
-
-void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
-
-	/*variables: */
-	Vector<IssmDouble>*    yg    = NULL;
-	Nodes *nodes = NULL;
-
-	if(VerboseSolution()) _printf0_("   updating boundary conditions...\n");
-
-	/*set current analysis: */
-	femmodel->SetCurrentConfiguration(analysis_type);
-
-	/*recover nodes: */
-	nodes=femmodel->nodes;
-
-	/*retrieve boundary conditions from element inputs :*/
-	GetSolutionFromInputsx(&yg,femmodel);
-
-	/*update spcs using this new vector of constraints: */
-	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
-
-	/*Free ressources:*/
-	delete yg;
-}
Index: /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 16560)
@@ -0,0 +1,44 @@
+#include "./SmoothedSurfaceSlopeXAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  SmoothedSurfaceSlopeXAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+	}
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	iomodel->FetchData(1,MeshVertexonbedEnum);
+	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeXAnalysisEnum,P1Enum);
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file SmoothedSurfaceSlopeXAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _SmoothedSurfaceSlopeXAnalysis_
+#define _SmoothedSurfaceSlopeXAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class SmoothedSurfaceSlopeXAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 16560)
@@ -0,0 +1,44 @@
+#include "./SmoothedSurfaceSlopeYAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  SmoothedSurfaceSlopeYAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	if(iomodel->meshtype==Mesh2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+	}
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	iomodel->FetchData(1,MeshVertexonbedEnum);
+	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeYAnalysisEnum,P1Enum);
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file SmoothedSurfaceSlopeYAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _SmoothedSurfaceSlopeYAnalysis_
+#define _SmoothedSurfaceSlopeYAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class SmoothedSurfaceSlopeYAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 16560)
@@ -0,0 +1,798 @@
+#include "./StressbalanceAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  StressbalanceAnalysis::DofsPerNode(int** pdoftype,int meshtype,int approximation){/*{{{*/
+
+	/*output*/
+	int *doftype = NULL;
+	int  numdofs;
+
+	switch(approximation){
+		case SSAApproximationEnum:  numdofs =2; break;
+		case L1L2ApproximationEnum: numdofs =2; break;
+		case HOApproximationEnum:   numdofs =2; break;
+		case SIAApproximationEnum:  numdofs =2; break;
+		case FSvelocityEnum:
+			 switch(meshtype){
+				 case Mesh3DEnum:         numdofs=3; break;
+				 case Mesh2DverticalEnum: numdofs=2; break;
+				 default: _error_("mesh type not supported yet");
+			}
+			break;
+		case FSpressureEnum: numdofs=1; break;
+		case NoneApproximationEnum:
+			 switch(meshtype){
+				 case Mesh3DEnum:         numdofs=4; break;
+				 case Mesh2DverticalEnum: numdofs=3; break;
+				 default: _error_("mesh type not supported yet");
+			}
+			break;
+		case SSAHOApproximationEnum:
+			numdofs=4;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=SSAApproximationEnum;
+			doftype[1]=SSAApproximationEnum;
+			doftype[2]=HOApproximationEnum;
+			doftype[3]=HOApproximationEnum;
+			break;
+		case HOFSApproximationEnum:
+			numdofs=5;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=HOApproximationEnum;
+			doftype[1]=HOApproximationEnum;
+			doftype[2]=FSvelocityEnum;
+			doftype[3]=FSvelocityEnum;
+			doftype[4]=FSvelocityEnum;
+			break;
+		case SSAFSApproximationEnum:
+			numdofs=5;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=SSAApproximationEnum;
+			doftype[1]=SSAApproximationEnum;
+			doftype[2]=FSvelocityEnum;
+			doftype[3]=FSvelocityEnum;
+			doftype[4]=FSvelocityEnum;
+			break;
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not implemented yet");
+	}
+
+	/*Assign output pointer and return*/
+	*pdoftype = doftype;
+	return numdofs;
+}/*}}}*/
+void StressbalanceAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*Intermediaries*/
+	int         numoutputs;
+	char**      requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSIAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSSAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsL1L2Enum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsHOEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationFeFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceIsnewtonEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalancePenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceFSreconditioningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceShelfDampeningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceViscosityOvershootEnum));
+
+	/*Requested outputs*/
+	iomodel->FetchData(&requestedoutputs,&numoutputs,StressbalanceRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(StressbalanceNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(StressbalanceRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,StressbalanceRequestedOutputsEnum);
+
+}/*}}}*/
+void StressbalanceAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Intermediaries*/
+	int    materials_type,finiteelement;
+	int    approximation;
+	int*   finiteelement_list=NULL;
+	bool   isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool   control_analysis;
+	bool   dakota_analysis;
+
+	/*Fetch constants needed: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
+
+	/*return if no processing required*/
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Fetch data needed and allocate vectors: */
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+	finiteelement_list=xNewZeroInit<int>(iomodel->numberofelements);
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*Get finite element type*/
+	if(!iscoupling){
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS)   iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		for(int i=0;i<iomodel->numberofelements;i++){
+			finiteelement_list[i]=finiteelement;
+		}
+	}
+	else{
+		if(isFS){
+			for(int i=0;i<iomodel->numberofelements;i++){
+				approximation=reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[i]);
+				if(approximation==FSApproximationEnum || approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+					finiteelement_list[i]=MINIcondensedEnum;
+				}
+				else{
+					finiteelement_list[i]=P1Enum;
+				}
+			}
+		}
+		else{
+			finiteelement = P1Enum;
+			for(int i=0;i<iomodel->numberofelements;i++){
+				finiteelement_list[i]=finiteelement;
+			}
+		}
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement_list[i]);
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
+	iomodel->FetchDataToInput(elements,DamageDEnum);
+
+	if(iomodel->meshtype==Mesh3DEnum){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+		iomodel->FetchDataToInput(elements,FlowequationBorderFSEnum);
+		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
+		iomodel->FetchDataToInput(elements,VzEnum,0.);
+		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
+	}
+	if(isFS){
+		iomodel->FetchDataToInput(elements,MeshVertexonbedEnum);
+		iomodel->FetchDataToInput(elements,PressureEnum,0.);
+		if(dakota_analysis)elements->InputDuplicate(PressureEnum,QmuPressureEnum);
+	}
+
+#ifdef _HAVE_ANDROID_
+	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
+#endif
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+	xDelete<int>(finiteelement_list);
+}/*}}}*/
+void StressbalanceAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	bool isSSA,isL1L2,isHO,isFS,iscoupling;
+	int  finiteelement=-1,approximation=-1;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, check that we have non SIA elements */
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular CreateNodes, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA){
+			approximation=SSAApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		}
+		else if(isL1L2){
+			approximation = L1L2ApproximationEnum;
+			finiteelement = P1Enum;
+		}
+		else if(isHO){
+			approximation = HOApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		}
+		else if(isFS){
+			approximation = FSApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		}
+		iomodel->FetchData(3,FlowequationBorderSSAEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderFSEnum);
+		::CreateNodes(nodes,iomodel,StressbalanceAnalysisEnum,finiteelement,approximation);
+		iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+	else{
+		/*Coupling: we are going to create P1 Elements only*/
+
+		Node*  node  = NULL;
+		int    lid=0;
+		if(!nodes) nodes = new Nodes();
+
+		iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(isFS){
+			/*P1+ velocity*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					if(approximation==FSApproximationEnum)  approximation=FSvelocityEnum;
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,approximation));
+				}
+			}
+			for(int i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,StressbalanceAnalysisEnum,FSvelocityEnum);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			/*P1 pressure*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,StressbalanceAnalysisEnum,FSpressureEnum);
+					if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum){
+						node->Deactivate();
+					}
+					nodes->AddObject(node);
+				}
+			}
+		}
+		else{
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])));
+				}
+			}
+		}
+		iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+}/*}}}*/
+void StressbalanceAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        i,j;
+	int        count,finiteelement;
+	IssmDouble g;
+	IssmDouble rho_ice;
+	IssmDouble FSreconditioning;
+	bool       isSIA,isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool       spcpresent = false;
+	int        Mx,Nx;
+	int        My,Ny;
+	int        Mz,Nz;
+	IssmDouble *spcvx          = NULL;
+	IssmDouble *spcvy          = NULL;
+	IssmDouble *spcvz          = NULL;
+	IssmDouble *nodeonSSA = NULL;
+	IssmDouble *nodeonHO   = NULL;
+	IssmDouble *nodeonFS   = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *groundedice_ls = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *surface        = NULL;
+	IssmDouble *z              = NULL;
+	IssmDouble *timesx=NULL;
+	IssmDouble *timesy=NULL;
+	IssmDouble *timesz=NULL;
+   IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&g,ConstantsGEnum);
+	iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Do we have coupling*/
+	if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular IoModelToConstraintsx, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS){  iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+			/*Deduce velocity interpolation from finite element*/
+			switch(finiteelement){
+				case P1P1Enum          : finiteelement = P1Enum;       break;
+				case P1P1GLSEnum       : finiteelement = P1Enum;       break;
+				case MINIcondensedEnum : finiteelement = P1bubbleEnum; break;
+				case MINIEnum          : finiteelement = P1bubbleEnum; break;
+				case TaylorHoodEnum    : finiteelement = P2Enum;       break;
+				default: _error_("finite element "<<finiteelement<<" not supported");
+			}
+		}
+		else{
+			_error_("model not supported yet");
+		}
+
+		if(isFS){
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+			iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+			iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+			if(iomodel->meshtype==Mesh3DEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->meshtype==Mesh2DverticalEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					if(nodeonbed[i]>0. && groundedice_ls[i]>0. && nodeonFS[i]>0.){
+						if(vertices_type[i] == FSApproximationEnum){
+							for(j=0;j<Nz;j++) spcvz[i*Nz+j] = 0.;
+						}
+						else{
+							_error_("not supported");
+						}
+					}
+				}
+			}
+			if(iomodel->meshtype==Mesh3DEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,1);
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,2);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,3);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->meshtype==Mesh2DverticalEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,1);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,2);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+			iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+			iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+
+			/*Pressure spc*/
+			count = constraints->Size();
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+			iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+			switch(finiteelement){
+				case P1bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,1,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2Enum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,1,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				default:
+					_error_("not implemented yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(surface,SurfaceEnum);
+			iomodel->DeleteData(z,MeshZEnum);
+		}
+		else{
+			IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,1);
+			IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,2);
+		}
+
+		return;
+	}
+
+	/*Constraints: fetch data: */
+	iomodel->FetchData(&spcvx,&Mx,&Nx,StressbalanceSpcvxEnum);
+	iomodel->FetchData(&spcvy,&My,&Ny,StressbalanceSpcvyEnum);
+	iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+	iomodel->FetchData(&nodeonSSA,NULL,NULL,FlowequationBorderSSAEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->FetchData(&nodeonHO,NULL,NULL,FlowequationBorderHOEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+	iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+	iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+	iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+
+	/*Initialize counter: */
+	count=0;
+
+	/*figure out times: */
+	timesx=xNew<IssmDouble>(Nx);
+	for(j=0;j<Nx;j++){
+		timesx[j]=spcvx[(Mx-1)*Nx+j];
+	}
+	/*figure out times: */
+	timesy=xNew<IssmDouble>(Ny);
+	for(j=0;j<Ny;j++){
+		timesy[j]=spcvy[(My-1)*Ny+j];
+	}
+	/*figure out times: */
+	timesz=xNew<IssmDouble>(Nz);
+	for(j=0;j<Nz;j++){
+		timesz[j]=spcvz[(Mz-1)*Nz+j];
+	}
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Start with adding spcs of coupling: zero at the border SSA/HO for the appropriate dofs*/
+			if(reCast<int,IssmDouble>(vertices_type[i]==SSAHOApproximationEnum)){
+				/*If grionSSA, spc HO dofs: 3 & 4*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else _error_("if vertices_type is SSAHO, you shoud have nodeonHO or nodeonSSA");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==HOFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc HO nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is HOFS, you shoud have nodeonHO or nodeonFS");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==SSAFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc SSA nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is SSAFS, you shoud have nodeonSSA or nodeonFS");
+			}
+			/*Now add the regular spcs*/
+			else{
+				if (Mx==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvx[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+
+				}
+				else if (Mx==iomodel->numberofvertices+1) {
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Nx);
+					spcpresent=false;
+					for(j=0;j<Nx;j++){
+						values[j]=spcvx[i*Nx+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,Nx,timesx,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (My==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
+					count++;
+				}
+				else if (My==iomodel->numberofvertices+1){
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Ny);
+					spcpresent=false;
+					for(j=0;j<Ny;j++){
+						values[j]=spcvy[i*Ny+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,Ny,timesy,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (reCast<int,IssmDouble>(vertices_type[i])==FSApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
+					if (Mz==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+						count++;
+					}
+					else if (Mz==iomodel->numberofvertices+1){
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(Nz);
+						spcpresent=false;
+						for(j=0;j<Nz;j++){
+							values[j]=spcvz[i*Nz+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,Nz,timesz,values,StressbalanceAnalysisEnum));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+
+				}
+				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,1,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum)); //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 (iomodel->meshtype==Mesh3DEnum) if(nodeonbed[i]>0. && groundedice_ls[i]>=0. && nodeonFS[i]>0.){
+				 switch(reCast<int,IssmDouble>(vertices_type[i])){
+					case SSAFSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					case HOFSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					case FSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					default: _error_("Vertex approximation " << EnumToStringx(reCast<int,IssmDouble>(vertices_type[i])) << " not supported");
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(spcvx,StressbalanceSpcvxEnum);
+	iomodel->DeleteData(spcvy,StressbalanceSpcvyEnum);
+	iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+	iomodel->DeleteData(nodeonSSA,FlowequationBorderSSAEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->DeleteData(nodeonHO,FlowequationBorderHOEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+	if(iomodel->meshtype==Mesh3DEnum)iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+	iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+	iomodel->DeleteData(surface,SurfaceEnum);
+	iomodel->DeleteData(z,MeshZEnum);
+
+	/*Free resources:*/
+	xDelete<IssmDouble>(timesx);
+	xDelete<IssmDouble>(timesy);
+	xDelete<IssmDouble>(timesz);
+	xDelete<IssmDouble>(values);
+
+}/*}}}*/
+void StressbalanceAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	const int   RIFTINFOSIZE = 12;
+	int         i;
+	int         count;
+	int         penpair_ids[2];
+	bool        isSSA,isL1L2,isHO,isFS;
+	int         numpenalties,numrifts,numriftsegments;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *penalties      = NULL;
+	int         assert_int;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Initialize counter: */
+	count=0;
+
+	/*Create Penpair for penalties: */
+	iomodel->FetchData(&penalties,&numpenalties,NULL,StressbalanceVertexPairingEnum);
+
+	for(i=0;i<numpenalties;i++){
+
+		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			assert_int=iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+1]-1)]; _assert_(assert_int);
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(iomodel->loadcounter+count+1,&penpair_ids[0],StressbalanceAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(penalties,StressbalanceVertexPairingEnum);
+
+	/*Create Riffront loads for rifts: */
+#ifdef _HAVE_RIFTS_
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
+		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		for(i=0;i<numriftsegments;i++){
+			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
+				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,StressbalanceAnalysisEnum));
+				count++;
+			}
+		}
+		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		xDelete<IssmDouble>(riftinfo);
+	}
+#endif
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/StressbalanceAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file StressbalanceAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceAnalysis_
+#define _StressbalanceAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 16560)
@@ -0,0 +1,133 @@
+#include "./StressbalanceSIAAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  StressbalanceSIAAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 2;
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Fetch data needed: */
+	bool   isSIA;
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag SIA on? otherwise, do nothing: */
+	if (!isSIA)return;
+
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool  isSIA;
+	Node* node = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if(!isSIA) return;
+
+	/*First create nodes*/
+	int    lid=0;
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Create new node if is in this processor's partition*/
+			node = new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceSIAAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]));
+
+			/*Deactivate node if not SIA*/
+			if(reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
+				node->Deactivate();
+			}
+
+			/*Add to Nodes dataset*/
+			nodes->AddObject(node);
+		}
+	}
+
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        count;
+	IssmDouble yts;
+	bool       isSIA;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if (!isSIA) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+	/*Initialize conunter*/
+	count=0;
+
+	/*vx and vy are spc'd if we are not on nodeonSIA: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i])){
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceSIAAnalysisEnum));
+				count++;
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceSIAAnalysisEnum));
+				count++;
+			}
+			else{
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvxEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,iomodel->Data(StressbalanceSpcvxEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+				}
+
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvyEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,iomodel->Data(StressbalanceSpcvyEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file StressbalanceSIAAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceSIAAnalysis_
+#define _StressbalanceSIAAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceSIAAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 16560)
@@ -0,0 +1,95 @@
+#include "./StressbalanceVerticalAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  StressbalanceVerticalAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
+
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->meshtype!=Mesh3DEnum) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->meshtype!=Mesh3DEnum) return;
+
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	::CreateNodes(nodes,iomodel,StressbalanceVerticalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int count;
+	IssmDouble yts;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*return if not 3d mesh*/
+	if(iomodel->meshtype!=Mesh3DEnum) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+	/*Initialize counter*/
+	count=0;
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationBorderFSEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceVerticalAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for FS
+				count++;
+			}
+			else if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvzEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,
+								iomodel->Data(StressbalanceSpcvzEnum)[i]/yts,StressbalanceVerticalAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+				count++;
+
+			}
+		} 
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file StressbalanceVerticalAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceVerticalAnalysis_
+#define _StressbalanceVerticalAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceVerticalAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 16560)
+++ /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 16560)
@@ -0,0 +1,94 @@
+#include "./ThermalAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ThermalAnalysis::DofsPerNode(int** doflist,int meshtype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ThermalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void ThermalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->meshtype==Mesh2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	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,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	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);
+	InputUpdateFromConstantx(elements,0.,VxMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
+	}
+}/*}}}*/
+void ThermalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype==Mesh3DEnum) iomodel->FetchData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,ThermalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void ThermalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Only 3d mesh supported*/
+	if(iomodel->meshtype==Mesh3DEnum){
+		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum,P1Enum);
+	}
+
+}/*}}}*/
+void ThermalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	if(iomodel->meshtype==Mesh2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+	/*create penalties for nodes: no node can have a temperature over the melting point*/
+	iomodel->FetchData(1,ThermalSpctemperatureEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+			if (xIsNan<IssmDouble>(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,ThermalSpctemperatureEnum);
+
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/ThermalAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 16560)
+++ /issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 16560)
@@ -0,0 +1,21 @@
+/*! \file ThermalAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _THERMALANALYSIS_
+#define _THERMALANALYSIS_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ThermalAnalysis: public Analysis{
+
+	public:
+		int  DofsPerNode(int** doflist,int meshtype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+};
+#endif
Index: sm/trunk/src/c/analyses/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/WrapperCorePointerFromSolutionEnum.cpp	(revision 16559)
+++ 	(revision )
@@ -1,57 +1,0 @@
-/*!\file:  WrapperCorePointerFromSolutionEnum.cpp
- * \brief: return type of analyses, number of analyses and core solution function.
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore){
-
-	/*output: */
-	void (*solutioncore)(FemModel*)=NULL;
-
-	/*parameters: */
-	bool control_analysis=false;
-	bool tao_analysis=false;
-	bool dakota_analysis=false;
-
-	/* retrieve some parameters that tell us whether wrappers are allowed, or whether we return 
-	 * a pure core. Wrappers can be dakota_core (which samples many solution_cores) or control_core (which 
-	 * carries out adjoint based inversion on a certain core: */
-	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	parameters->FindParam(&control_analysis,InversionIscontrolEnum);
-	parameters->FindParam(&tao_analysis,InversionTaoEnum);
-
-	if(nodakotacore)dakota_analysis=false;
-
-	if(dakota_analysis){
-		#ifdef _HAVE_DAKOTA_
-		solutioncore=dakota_core;
-		#else
-		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
-		#endif
-	}
-	else if(control_analysis){
-		#ifdef _HAVE_CONTROL_
-		if(tao_analysis) solutioncore=controltao_core;
-		else solutioncore=control_core;
-		#else
-		_error_("ISSM was not compiled with control support, cannot carry out control analysis!");
-		#endif
-	}
-	else CorePointerFromSolutionEnum(&solutioncore,parameters,solutiontype);  /*This means we retrieve a core solution that is not a wrapper*/
-
-	/*Assign output pointer:*/
-	_assert_(psolutioncore);
-	*psolutioncore=solutioncore;
-
-}
Index: sm/trunk/src/c/analyses/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ad_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,320 +1,0 @@
-/*!\file ad_core
- * \brief: compute outputs from the AD mode,  using our dependents and independents, and drivers available in Adolc.
- */
-
-/*Includes: {{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <set>
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-/*}}}*/
-
-void ad_core(FemModel* femmodel){
-
-	/*diverse: */
-	int     i;
-	int     dummy;
-	int     num_dependents=0;
-	int     num_independents=0;
-	bool    isautodiff       = false;
-	char   *driver           = NULL;
-	size_t  tape_stats[11];
-
-	/*state variables: */
-	IssmDouble *axp = NULL;
-	double     *xp  = NULL;
-	int my_rank=IssmComm::GetRank();
-
-
-	/*AD mode on?: */
-	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
-
-	if(isautodiff){
-
-		#ifdef _HAVE_ADOLC_
-
-			/*First, stop tracing: */
-			trace_off();
-
-			/*preliminary checks: */
-			if (my_rank==0) {
-				femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
-				femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
-				if(!(num_dependents*num_independents)) return;
-			}
-
-			if(VerboseAutodiff())_printf0_("   start ad core\n");
-
-			/*retrieve state variable: */
-			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
-
-			/* driver argument */
-			xp=xNew<double>(num_independents);
-			for(i=0;i<num_independents;i++){
-				xp[i]=reCast<double,IssmDouble>(axp[i]);
-			}
-
-			/*get the EDF pointer:*/
-			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
-
-			/*Branch according to AD driver: */
-			femmodel->parameters->FindParam(&driver,AutodiffDriverEnum);
-
-			/* these are always needed regardless of the interpreter */
-			anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
-			anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
-
-			if (strcmp(driver,"fos_forward")==0){
-
-				int     anIndepIndex;
-				double *tangentDir         = NULL;
-				double *jacTimesTangentDir = NULL;
-				double *theOutput          = NULL;
-
-				/*retrieve direction index: */
-				femmodel->parameters->FindParam(&anIndepIndex,AutodiffFosForwardIndexEnum);
-
-				if (anIndepIndex<0 || anIndepIndex>=num_independents) _error_("index value for AutodiffFosForwardIndexEnum should be in [0,num_independents-1]");
-
-				tangentDir=xNewZeroInit<double>(num_independents);
-				tangentDir[anIndepIndex]=1.0;
-
-				jacTimesTangentDir=xNew<double>(num_dependents);
-				theOutput=xNew<double>(num_dependents);
-
-				/*set the forward method function pointer: */
-#ifdef _HAVE_GSL_
-				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
-#endif
-
-				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
-				anEDF_for_solverx_p->dp_X=xNew<double>(anEDF_for_solverx_p->max_n);
-				anEDF_for_solverx_p->dp_Y=xNew<double>(anEDF_for_solverx_p->max_m);
-
-				/*call driver: */
-				fos_forward(my_rank,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
-
-				/*add to results*/
-				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,jacTimesTangentDir,num_dependents,1,1,0.0));
-
-				/*free resources :*/
-				xDelete(theOutput);
-				xDelete(jacTimesTangentDir);
-				xDelete(tangentDir);
-			}
-			else if ((strcmp(driver,"fov_forward")==0) || (strcmp(driver,"fov_forward_all")==0)){
-
-				int      tangentDirNum;
-				int      dummy;
-				int     *indepIndices  = NULL;
-				double **jacTimesSeed  = NULL;
-				double **seed          = NULL;
-				double  *theOutput     = NULL;
-				std::set<unsigned int> anIndexSet;
-
-				/*retrieve directions:*/
-				if (strcmp(driver,"fov_forward_all")==0){
-					tangentDirNum=num_independents;
-					indepIndices=xNewZeroInit<int>(tangentDirNum);
-					for(i=0;i<num_independents;i++)indepIndices[i]=1;
-				}
-				else{
-					femmodel->parameters->FindParam(&indepIndices,&tangentDirNum,&dummy,AutodiffFovForwardIndicesEnum);
-				}
-
-				/*Some checks: */
-				if (tangentDirNum<1 || tangentDirNum>num_independents) _error_("tangentDirNum should be in [1,num_independents]");
-
-				/* full Jacobian or Jacobian projection:*/
-				jacTimesSeed=xNew<double>(num_dependents,tangentDirNum);
-
-				/*set the forward method function pointers: */
-#ifdef _HAVE_GSL_
-				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
-#endif
-				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
-
-				/*allocate the space for the parameters to invoke EDF fov_forward:*/
-				anEDF_for_solverx_p->dpp_X=xNew<double>(anEDF_for_solverx_p->max_n, tangentDirNum);
-				anEDF_for_solverx_p->dpp_Y=xNew<double>(anEDF_for_solverx_p->max_m, tangentDirNum);
-
-				/*seed matrix: */
-				seed=xNewZeroInit<double>(num_independents,tangentDirNum);
-
-				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
-				for (int i=0; i<tangentDirNum; ++i) {
-					/* make sure the index is in range*/
-					if (indepIndices[i]>num_independents) {
-						_error_("indepIndices values must be in [0,num_independents-1]");
-					}
-					if (anIndexSet.find(indepIndices[i])!=anIndexSet.end()) {
-						_error_("duplicate indepIndices values are not allowed until we implement Jacobian decompression");
-					}
-					anIndexSet.insert(indepIndices[i]);
-					/* now populate the seed matrix from the set of independent indices;
-					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
-					seed[indepIndices[i]][i]=1.0;
-				}
-
-				/*allocate output: */
-				theOutput=xNew<double>(num_dependents);
-
-				/*call driver: */
-				fov_forward(my_rank,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
-				/*Free resources: */
-				xDelete(theOutput);
-				xDelete(indepIndices);
-				xDelete(seed);
-
-				/*add to results: */
-				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*jacTimesSeed,num_dependents*tangentDirNum,1,1,0.0));
-
-				/*Free resources: */
-				xDelete(jacTimesSeed);
-				xDelete(indepIndices);
-			}
-			else if (strcmp(driver,"fos_reverse")==0) {
-
-				int     aDepIndex=0;
-				double *aWeightVector=NULL;
-				double *weightVectorTimesJac=NULL;
-
-				/*retrieve direction index: */
-				femmodel->parameters->FindParam(&aDepIndex,AutodiffFosReverseIndexEnum);
-				aWeightVector=xNewZeroInit<double>(num_dependents);
-				if (my_rank==0) {
-					if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
-					aWeightVector[aDepIndex]=1.0;
-				}
-				weightVectorTimesJac=xNew<double>(num_independents);
-
-				/*set the forward method function pointer: */
-#ifdef _HAVE_GSL_
-				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
-#endif
-#ifdef _HAVE_MUMPS_
-				anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
-#endif
-
-				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
-				anEDF_for_solverx_p->dp_U=xNew<double>(anEDF_for_solverx_p->max_m);
-				anEDF_for_solverx_p->dp_Z=xNew<double>(anEDF_for_solverx_p->max_n);
-
-				/*call driver: */
-				fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
-				if(VerboseAutodiff())_printf_("   done with fos_reverse\n");
-
-				/*add to results*/
-				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,weightVectorTimesJac,num_independents,1,1,0.0));
-
-				/*free resources :*/
-				xDelete(weightVectorTimesJac);
-				xDelete(aWeightVector);
-			}
-			else if ((strcmp(driver,"fov_reverse")==0) || (strcmp(driver,"fov_reverse_all")==0)){
-
-				int* depIndices=NULL;
-				int weightNum;
-				int dummy;
-				double **weightsTimesJac=NULL;
-				double **weights=NULL;
-				std::set<unsigned int> anIndexSet;
-
-				/*retrieve directions:*/
-				if (strcmp(driver,"fov_reverse_all")==0){
-					weightNum=num_dependents;
-					depIndices=xNewZeroInit<int>(weightNum);
-					for(i=0;i<num_dependents;i++)depIndices[i]=1;
-				}
-				else{
-					femmodel->parameters->FindParam(&depIndices,&weightNum,&dummy,AutodiffFovForwardIndicesEnum);
-				}
-
-				/*Some checks: */
-				if (weightNum<1 || weightNum>num_dependents) _error_("tangentDirNum should be in [1,num_dependents]");
-
-				/* full Jacobian or Jacobian projection:*/
-				weightsTimesJac=xNew<double>(weightNum,num_independents);
-
-				/*set the forward method function pointers: */
-#ifdef _HAVE_GSL_
-				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
-#endif
-
-				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
-				anEDF_for_solverx_p->dpp_U=xNew<double>(weightNum,anEDF_for_solverx_p->max_m);
-				anEDF_for_solverx_p->dpp_Z=xNew<double>(weightNum,anEDF_for_solverx_p->max_n);
-
-				/*seed matrix: */
-				weights=xNewZeroInit<double>(weightNum,num_dependents);
-
-				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
-				for (int i=0; i<weightNum; ++i) {
-					/* make sure the index is in range*/
-					if (depIndices[i]>num_dependents) {
-						_error_("depIndices values must be in [0,num_dependents-1]");
-					}
-					if (anIndexSet.find(depIndices[i])!=anIndexSet.end()) {
-						_error_("duplicate depIndices values are not allowed until we implement Jacobian decompression");
-					}
-					anIndexSet.insert(depIndices[i]);
-					/* now populate the seed matrix from the set of independent indices;
-					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
-					weights[depIndices[i]][i]=1.0;
-				}
-
-				/*call driver: */
-				fov_reverse(my_rank,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
-
-				/*add to results: */
-				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*weightsTimesJac,weightNum*num_independents,1,1,0.0));
-
-				/*Free resources: */
-				xDelete(weights);
-				xDelete(weightsTimesJac);
-				xDelete(depIndices);
-			}
-			else _error_("driver: " << driver << " not yet supported!");
-
-			/* delete the allocated space for the parameters:*/
-			xDelete(anEDF_for_solverx_p->dp_x);
-			xDelete(anEDF_for_solverx_p->dp_X);
-			xDelete(anEDF_for_solverx_p->dpp_X);
-			xDelete(anEDF_for_solverx_p->dp_y);
-			xDelete(anEDF_for_solverx_p->dp_Y);
-			xDelete(anEDF_for_solverx_p->dpp_Y);
-			xDelete(anEDF_for_solverx_p->dp_U);
-			xDelete(anEDF_for_solverx_p->dpp_U);
-			xDelete(anEDF_for_solverx_p->dp_Z);
-			xDelete(anEDF_for_solverx_p->dpp_Z);
-
-			/*Print statistics:*/
-			tapestats(my_rank,tape_stats); //reading of tape statistics
-			if(VerboseAutodiff()){
-				_printf0_("   ADOLC statistics: \n");
-				_printf0_("   "<<setw(45)<<left<<"Number of independents: " <<tape_stats[0] << "\n");
-				_printf0_("   "<<setw(45)<<left<<"Number of dependents: " <<tape_stats[1] << "\n");
-				_printf0_("   "<<setw(45)<<left<<"Maximal number of live active variables: " <<tape_stats[2] << "\n");
-				_printf0_("   "<<setw(45)<<left<<"Size of value stack (number of overwrites): " <<tape_stats[3] << "\n");
-				_printf0_("   "<<setw(45)<<left<<"Buffer size (a multiple of eight): " <<tape_stats[4] << "\n");
-				_printf0_("   "<<setw(45)<<left<<"Total number of operations recorded: " <<tape_stats[5] << "\n");
-			}
-			if(VerboseAutodiff())_printf0_("   end AD core\n");
-
-			/*Free resources: */
-			xDelete(xp);
-			xDelete(axp); 
-		#else
-			_error_("Should not be requesting AD drivers when an AD library is not available!");
-		#endif
-	}
-}
Index: sm/trunk/src/c/analyses/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,38 +1,0 @@
-/*!\file:  adjointbalancethickness_core.cpp
- * \brief compute inverse method adjoint state
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void adjointbalancethickness_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-	/*retrieve parameters:*/
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	/*compute thickness */
-	if(VerboseSolution()) _printf0_("   computing thickness\n");
-	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	/*Call SurfaceAreax, because some it might be needed by PVector*/
-	SurfaceAreax(NULL,femmodel);
-
-	/*compute adjoint*/
-	if(VerboseSolution()) _printf0_("   computing adjoint\n");
-	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
-	solutionsequence_adjoint_linear(femmodel);
-
-	/*Save results*/
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,AdjointEnum);
-	}
-}
Index: sm/trunk/src/c/analyses/adjointstressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointstressbalance_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,46 +1,0 @@
-/*!\file:  adjointstressbalance_core.cpp
- * \brief compute inverse method adjoint state
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void adjointstressbalance_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool isFS;
-	bool save_results;
-	bool conserve_loads   = true;
-
-	/*retrieve parameters:*/
-	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	/*Compute velocities*/
-	if(VerboseSolution()) _printf0_("   computing velocities\n");
-	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-	solutionsequence_nonlinear(femmodel,conserve_loads); 
-
-	/*Call SurfaceAreax, because some it might be needed by PVector*/
-	SurfaceAreax(NULL,femmodel);
-
-	/*Compute adjoint*/
-	if(VerboseSolution()) _printf0_("   computing adjoint\n");
-	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum,AdjointHorizAnalysisEnum);
-	solutionsequence_adjoint_linear(femmodel);
-
-	/*Save results*/
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,AdjointxEnum);
-		InputToResultx(femmodel,AdjointyEnum);
-		if (isFS){
-			InputToResultx(femmodel,AdjointzEnum);
-			InputToResultx(femmodel,AdjointpEnum);
-		}
-	}
-}
Index: /issm/trunk/src/c/analyses/analyses.h
===================================================================
--- /issm/trunk/src/c/analyses/analyses.h	(revision 16559)
+++ /issm/trunk/src/c/analyses/analyses.h	(revision 16560)
@@ -6,54 +6,32 @@
 #define _ANALYSES_H_
 
-/*forward declarations: */
-struct OptArgs;
-class FemModel;
-class Parameters;
-template <class doubletype> class Matrix;
-template <class doubletype> class Vector;
+#include "./Analysis.h"
 
-#include "../shared/io/Comm/IssmComm.h"
-#include "../shared/Numerics/types.h"
+#include "./AdjointBalancethicknessAnalysis.h"
+#include "./AdjointHorizAnalysis.h"
+#include "./BalancethicknessAnalysis.h"
+#include "./BalancethicknessSoftAnalysis.h"
+#include "./BalancevelocityAnalysis.h"
+#include "./DamageEvolutionAnalysis.h"
+#include "./EnthalpyAnalysis.h"
+#include "./ExtrudeFromBaseAnalysis.h"
+#include "./ExtrudeFromTopAnalysis.h"
+#include "./FreeSurfaceBaseAnalysis.h"
+#include "./FreeSurfaceTopAnalysis.h"
+#include "./GiaAnalysis.h"
+#include "./HydrologyDCEfficientAnalysis.h"
+#include "./HydrologyDCInefficientAnalysis.h"
+#include "./HydrologyShreveAnalysis.h"
+#include "./MasstransportAnalysis.h"
+#include "./MeltingAnalysis.h"
+#include "./MeshdeformationAnalysis.h"
+#include "./SmoothedSurfaceSlopeXAnalysis.h"
+#include "./SmoothedSurfaceSlopeYAnalysis.h"
+#include "./StressbalanceAnalysis.h"
+#include "./StressbalanceSIAAnalysis.h"
+#include "./StressbalanceVerticalAnalysis.h"
+#include "./L2ProjectionBaseAnalysis.h"
+#include "./ThermalAnalysis.h"
 
-/*cores: */
-void adjointstressbalance_core(FemModel* femmodel);
-void adjointbalancethickness_core(FemModel* femmodel);
-void gradient_core(FemModel* femmodel,int n=0,bool orthogonalize=false);
-void stressbalance_core(FemModel* femmodel);
-void hydrology_core(FemModel* femmodel);
-void thermal_core(FemModel* femmodel);
-void enthalpy_core(FemModel* femmodel);
-void surfaceslope_core(FemModel* femmodel);
-void bedslope_core(FemModel* femmodel);
-void control_core(FemModel* femmodel);
-void controltao_core(FemModel* femmodel);
-void masstransport_core(FemModel* femmodel);
-void balancethickness_core(FemModel* femmodel);
-void balancevelocity_core(FemModel* femmodel);
-void slopecompute_core(FemModel* femmodel);
-void steadystate_core(FemModel* femmodel);
-void transient_core(FemModel* femmodel);
-void dakota_core(FemModel* femmodel);
-void ad_core(FemModel* femmodel);
-void dummy_core(FemModel* femmodel);
-void gia_core(FemModel* femmodel);
-IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
-
-//optimization
-int GradJSearch(IssmDouble* search_vector,FemModel* femmodel,int step);
-
-//diverse
-void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ptoolkitsname,char** plockname,char** prootpath,int argc,char **argv);
-void WriteLockFile(char* filename);
-void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
-ISSM_MPI_Comm EnvironmentInit(int argc,char** argv);
-void EnvironmentFinalize(void);
-void PrintBanner(void);
-
-//solution configuration
-void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype);
-void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
-void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
-void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
-
+#include "EnumToAnalysis.h"
 #endif
Index: sm/trunk/src/c/analyses/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/balancethickness_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,31 +1,0 @@
-/*!\file: balancethickness_core.cpp
- * \brief: core of the balancethickness solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void balancethickness_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-	/*activate formulation: */
-	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-
-	/*recover parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("call computational core:\n");
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,ThicknessEnum);
-	}
-
-}
Index: sm/trunk/src/c/analyses/balancevelocity_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/balancevelocity_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,39 +1,0 @@
-/*!\file: balancevelocity_core.cpp
- * \brief: core of the balancevelocity solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void balancevelocity_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-
-	/*recover parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("computing smoothed slopes:\n");
-	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SmoothedSurfaceSlopeXAnalysisEnum);
-	solutionsequence_linear(femmodel);
-	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SmoothedSurfaceSlopeYAnalysisEnum);
-	solutionsequence_linear(femmodel);
-	//surfaceslope_core(femmodel);
-
-	if(VerboseSolution()) _printf0_("call computational core:\n");
-	femmodel->SetCurrentConfiguration(BalancevelocityAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,SurfaceSlopeXEnum);
-		InputToResultx(femmodel,SurfaceSlopeYEnum);
-		InputToResultx(femmodel,VelEnum);
-	}
-
-}
Index: sm/trunk/src/c/analyses/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/bedslope_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,34 +1,0 @@
-/*!\file: bedslope_core.cpp
- * \brief: core of the slope solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void bedslope_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-	/*Recover some parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("   computing slope\n");
-
-	/*Call on core computations: */
-	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeXAnalysisEnum);
-	solutionsequence_linear(femmodel);
-	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,BedSlopeXEnum);
-		InputToResultx(femmodel,BedSlopeYEnum);
-	}
-
-}
Index: sm/trunk/src/c/analyses/control_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/control_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,148 +1,0 @@
-/*!\file: control_core.cpp
- * \brief: core of the control solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-/*Local prototypes*/
-bool controlconvergence(IssmDouble J, IssmDouble tol_cm);
-
-void control_core(FemModel* femmodel){
-
-	int     i;
-
-	/*parameters: */
-	int        num_controls,num_responses;
-	int        nsteps;
-	IssmDouble tol_cm;
-	bool       cm_gradient;
-	int        dim;
-	int        solution_type;
-	bool       isFS;
-	bool       dakota_analysis = false;
-
-	int        *control_type   = NULL;
-	IssmDouble *responses      = NULL;
-	int        *step_responses = NULL;
-	IssmDouble *maxiter        = NULL;
-	IssmDouble *cm_jump        = NULL;
-
-	/*intermediary: */
-	IssmDouble search_scalar = 1.;
-	OptArgs    optargs;
-	OptPars    optpars;
-
-	/*Solution and Adjoint core pointer*/
-	void (*solutioncore)(FemModel*) = NULL;
-	void (*adjointcore)(FemModel*)  = NULL;
-
-	/*output: */
-	IssmDouble* 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(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->SetParam(false,SaveResultsEnum);
-
-	/*out of solution_type, figure out solution core and adjoint function pointer*/
-	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
-	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
-
-	/*Launch once a complete solution to set up all inputs*/
-	if(VerboseControl()) _printf0_("   preparing initial solution\n");
-	if(isFS) solutioncore(femmodel);
-
-	/*Initialize responses: */
-	J=xNew<IssmDouble>(nsteps);
-	step_responses=xNew<int>(num_responses);
-
-	/*Initialize some of the BrentSearch arguments: */
-	optargs.femmodel=femmodel;
-	optpars.xmin=0; optpars.xmax=1;
-
-	/*Start looping: */
-	for(int n=0;n<nsteps;n++){
-
-		/*Display info*/
-		if(VerboseControl()) _printf0_("\n" << "   control method step " << n+1 << "/" << nsteps << "\n");
-		for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
-		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
-
-		/*In steady state inversion, compute new temperature field now*/
-		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
-
-		if(VerboseControl()) _printf0_("   compute adjoint state:\n");
-		adjointcore(femmodel);
-		gradient_core(femmodel,n,search_scalar==0.);
-
-		/*Return gradient if asked: */
-		if (cm_gradient){
-			InputToResultx(femmodel,GradientEnum);
-			goto cleanup_and_return;
-		}
-
-		if(VerboseControl()) _printf0_("   optimizing along gradient direction\n");
-		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
-		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
-
-		if(VerboseControl()) _printf0_("   updating parameter using optimized search scalar\n"); //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;
-	}
-
-	if(VerboseControl()) _printf0_("   preparing final solution\n");
-	femmodel->parameters->SetParam(true,SaveResultsEnum);
-	solutioncore(femmodel);
-
-	/*some results not computed by steadystate_core or stressbalance_core: */
-	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
-		for(i=0;i<num_controls;i++) InputToResultx(femmodel,control_type[i]);
-
-		#ifdef _HAVE_ADOLC_
-		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
-		for(i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
-		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
-		xDelete<IssmPDouble>(J_passive);
-		#else
-		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
-		#endif
-	}
-
-	cleanup_and_return:
-	/*Free ressources: */
-	xDelete<int>(control_type);
-	xDelete<int>(step_responses);
-	xDelete<IssmDouble>(maxiter);
-	xDelete<IssmDouble>(responses);
-	xDelete<IssmDouble>(cm_jump);
-	xDelete<IssmDouble>(J);
-}
-bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
-
-	bool converged=false;
-
-	/*Has convergence been reached?*/
-	if (!xIsNan<IssmDouble>(tol_cm) && J<tol_cm){
-		converged=true;
-		if(VerboseConvergence()) _printf0_("      Convergence criterion reached: J = " << J << " < " << tol_cm);
-	}
-
-	return converged;
-}
Index: sm/trunk/src/c/analyses/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/controltao_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,193 +1,0 @@
-/*!\file: control_core.cpp
- * \brief: core of the control solution 
- */ 
-#include <config.h>
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
-#include <tao.h>
-
-/*Local prototype*/
-int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
-int IssmMonitor(TaoSolver,void*);
-typedef struct {
-	FemModel* femmodel;
-	double*   J;
-} AppCtx;
-
-void controltao_core(FemModel* femmodel){
-
-	/*TAO*/
-	int                 ierr;
-	int                 num_controls,solution_type;
-	int                 nsteps,maxiter;
-	AppCtx              user;
-	TaoSolver           tao = 0;
-	IssmDouble         *dummy        = NULL;
-	int                *control_list = NULL;
-	Vector<IssmDouble> *X            = NULL;
-	Vector<IssmDouble> *G            = NULL;
-	Vector<IssmDouble> *XL           = NULL;
-	Vector<IssmDouble> *XU           = NULL;
-
-	/*Initialize TAO*/
-	int argc; char **args=NULL;
-	PetscGetArgs(&argc,&args);
-	ierr = TaoInitialize(&argc,&args,(char*)0,"");
-	if(ierr) _error_("Could not initialize Tao");
-
-	/*Recover some parameters*/
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	femmodel->parameters->FindParam(&control_list,NULL,InversionControlParametersEnum);
-	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
-	femmodel->parameters->SetParam(false,SaveResultsEnum);
-	maxiter=nsteps*10;
-
-	/*Prepare Toolkit*/
-	ToolkitsOptionsFromAnalysis(femmodel->parameters,DefaultAnalysisEnum);
-
-	/*Initialize TAO*/
-	TaoCreate(IssmComm::GetComm(),&tao);
-	if(VerboseControl()) _printf0_("   Initializing the Toolkit for Advanced Optimization (TAO)\n");
-	TaoSetFromOptions(tao);
-	TaoSetType(tao,"tao_blmvm");
-	//TaoSetType(tao,"tao_cg");
-	//TaoSetType(tao,"tao_lmvm");
-
-	/*Prepare all TAO parameters*/
-	TaoSetMonitor(tao,IssmMonitor,&user,NULL);
-	TaoSetMaximumFunctionEvaluations(tao,maxiter);
-	TaoSetMaximumIterations(tao,nsteps);
-	TaoSetTolerances(tao,0.,0.,0.,0.,0.);
-
-	GetVectorFromControlInputsx(&X, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
-	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
-	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
-	TaoSetInitialVector(tao,X->pvector->vector);
-	TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
-	delete XL;
-	delete XU;
-
-	user.J=xNewZeroInit<double>(maxiter+5);
-	user.femmodel=femmodel;
-	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
-
-	/*Solver optimization problem*/
-	if(VerboseControl()) _printf0_("   Starting optimization\n");
-	TaoSolve(tao);
-	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
-	TaoGetSolutionVector(tao,&X->pvector->vector);
-	G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
-	TaoGetGradientVector(tao,&G->pvector->vector);
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
-	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
-	for(int i=0;i<num_controls;i++){
-		InputToResultx(femmodel,control_list[i]);
-	}
-	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
-
-	/*Finalize*/
-	if(VerboseControl()) _printf0_("   preparing final solution\n");
-	femmodel->parameters->SetParam(true,SaveResultsEnum);
-	void (*solutioncore)(FemModel*)=NULL;
-	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
-	solutioncore(femmodel);
-
-	/*Clean up and return*/
-	xDelete<int>(control_list);
-	xDelete<double>(user.J);
-	delete X;
-	TaoDestroy(&tao);
-	TaoFinalize();
-}
-int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *userCtx){
-
-	/*Retreive arguments*/
-	int                  solution_type,num_cost_functions;
-	AppCtx              *user            = (AppCtx *)userCtx;
-	FemModel            *femmodel        = user->femmodel;
-	int                 *cost_functions  = NULL;
-	IssmDouble          *cost_functionsd = NULL;
-	Vector<IssmDouble>  *gradient        = NULL;
-	Vector<IssmDouble>  *X               = NULL;
-
-	/*Convert input to Vec*/
-	X=new Vector<IssmDouble>(Xpetsc);
-
-	/*Set new variable*/
-	//VecView(X,PETSC_VIEWER_STDOUT_WORLD);
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
-	delete X;
-
-	/*Recover some parameters*/
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&num_cost_functions,InversionNumCostFunctionsEnum);
-	femmodel->parameters->FindParam(&cost_functionsd,NULL,NULL,InversionCostFunctionsEnum);
-
-	/*Prepare objective function*/
-	cost_functions=xNew<int>(num_cost_functions);
-	for(int i=0;i<num_cost_functions;i++) cost_functions[i]=(int)cost_functionsd[i]; //FIXME
-	femmodel->parameters->SetParam(cost_functions,1,num_cost_functions,StepResponsesEnum);
-
-	/*Compute solution and adjoint*/
-	void (*solutioncore)(FemModel*)=NULL;
-	void (*adjointcore)(FemModel*)=NULL;
-	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
-	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
-	solutioncore(femmodel);
-	adjointcore(femmodel);
-
-	/*Compute objective function*/
-	femmodel->CostFunctionx(fcn);
-
-	/*Compute gradient*/
-	Gradjx(&gradient,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	VecCopy(gradient->pvector->vector,G); delete gradient;
-	VecScale(G,-1.);
-
-	/*Clean-up and return*/
-	xDelete<int>(cost_functions);
-	xDelete<IssmDouble>(cost_functionsd);
-	return 0;
-}
-int IssmMonitor(TaoSolver tao, void *userCtx){
-
-	int       i,its,num_responses;
-	IssmDouble    f,gnorm,cnorm,xdiff;
-	AppCtx   *user      = (AppCtx *)userCtx;
-	FemModel *femmodel  = user->femmodel;
-	Element  *element   = NULL;
-	int      *responses = NULL;
-
-	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	femmodel->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
-
-	TaoGetSolutionStatus(tao, &its, &f, &gnorm, &cnorm, &xdiff, NULL);
-	if(its==0) _printf0_("Iter       Function      Residual  |  List of contributions\n");
-	if(its==0) _printf0_("-----------------------------------+-----------------------\n");
-	_printf0_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
-	user->J[its]=f;
-
-	/*Retrieve objective functions independently*/
-	for(i=0;i<num_responses;i++){
-		femmodel->Responsex(&f,EnumToStringx(responses[i]),i);
-		_printf0_(" "<<setw(12)<<setprecision(7)<<f);
-	}
-	_printf0_("\n");
-
-	/*Clean-up and return*/
-	xDelete<int>(responses);
-	return 0;
-}
-
-#else
-void controltao_core(FemModel* femmodel){
-	_error_("TAO not installed or PETSc version not supported");
-}
-#endif //_HAVE_TAO_ 
Index: sm/trunk/src/c/analyses/dakota_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/dakota_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,232 +1,0 @@
-/*!\file:  dakota_core.cpp
- * \brief: wrapper to the Dakota capabilities. qmu fires up Dakota, and registers a Dakota Pluggin
- * which will be in charge of running the solution sequences repeteadly, to garner statistics. 
- *
- * This routine deals with running ISSM and Dakota in library mode. In library mode, Dakota does not 
- * run as an execuatble. Its capabilities are linked into the ISSM software. ISSM calls dakota routines 
- * directly from the dakota library. qmu.cpp is the code that is in charge of calling those routines. 
- *
- * Dakota has its own way of running in parallel (for embarassingly parallel jobs). We do not want that, 
- * as ISSM knows exactly how to run "really parallel" jobs that use all CPUS. To bypass Dakota's parallelism, 
- * we overloaded the constructor for the parallel library (see the Dakota patch in the externalpackages/dakota
- * directory). This overloaded constructor fires up Dakota serially on CPU 0 only! We take care of broadcasting 
- * to the other CPUS, hence ISSM is running in parallel, and Dakota serially on CPU0. 
- *
- * Now, how does CPU 0 drive all other CPUS to carry out sensitivity analysese? By synchronizing its call to 
- * our ISSM cores (stressbalance_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
- * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up DakotaSpawnCore.cpp, 
- * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
- * DakotaSpawnCore. In the end, DakotaSpawnCore is fired up on all CPUS, with CPU0 having Dakota inputs, that it will 
- * broacast to other CPUS. 
- *
- * Now, how does dakota call the DakotaSpawnCore routine? The DakotaSpawnCore is embedded into the DakotaPlugin object 
- * which is derived from the Direct Interface Dakota objct. This is the only way to run Dakota in library 
- * mode (see their developper guide for more info). Dakota registers the DakotaPlugin object into its own 
- * database, and calls on the embedded DakotaSpawnCore from CPU0. 
- *
- */ 
-
-/*include files: {{{*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../shared/shared.h"
-#include "../classes/classes.h"
-
-#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
-#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
-#include <ParallelLibrary.H>
-#include <ProblemDescDB.H>
-#include <DakotaStrategy.H>
-#include <DakotaModel.H>
-#include <DakotaInterface.H>
-#else
-#include <ParallelLibrary.hpp>
-#include <ProblemDescDB.hpp>
-#include <DakotaStrategy.hpp>
-#include <DakotaModel.hpp>
-#include <DakotaInterface.hpp>
-#endif
-#include "./DakotaSpawnCore.h"
-#endif
-/*}}}*/
-/*DakotaPlugin class {{{*/
-#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
-#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
-#include <DirectApplicInterface.H>
-#include <DakotaResponse.H>
-#include <ParamResponsePair.H>
-#include <system_defs.h>
-#include <ProblemDescDB.H>
-#include <ParallelLibrary.H>
-#else
-#include <DirectApplicInterface.hpp>
-#include <DakotaResponse.hpp>
-#include <ParamResponsePair.hpp>
-#include <ProblemDescDB.hpp>
-#include <ParallelLibrary.hpp>
-#endif
-namespace SIM {
-	class DakotaPlugin: public Dakota::DirectApplicInterface{
-		public:
-			/*these fields are used by core solutions: */
-			void *femmodel;
-			int   counter;
-			/*Constructors/Destructors*/
-			DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){/*{{{*/
-				femmodel = in_femmodel;
-				counter  = 0;
-			}/*}}}*/
-			~DakotaPlugin(){/*{{{*/
-				/* Virtual destructor handles referenceCount at Interface level. */ 
-			}/*}}}*/
-		protected:
-			/*execute the input filter portion of a direct evaluation invocation*/
-			//int derived_map_if(const Dakota::String& if_name);
-			/*execute an analysis code portion of a direct evaluation invocation*/
-			int derived_map_ac(const Dakota::String& driver){/*{{{*/
-
-				int i;
-				IssmDouble* variables=NULL;
-				char** variable_descriptors=NULL;
-				char*  variable_descriptor=NULL;
-				IssmDouble* responses=NULL;
-
-				/*increae counter: */
-				counter++;
-
-				/*Before launching analysis, we need to transfer the dakota inputs into Issm 
-				 *readable variables: */
-
-				/*First, the variables: */
-				variables=xNew<IssmDouble>(numACV);
-				for(i=0;i<numACV;i++){
-					variables[i]=xC[i];
-				}
-				/*The descriptors: */
-				variable_descriptors=xNew<char*>(numACV);
-				for(i=0;i<numACV;i++){
-					std::string label=xCLabels[i];
-					variable_descriptor=xNew<char>(strlen(label.c_str())+1);
-					memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
-
-					variable_descriptors[i]=variable_descriptor;
-				}
-
-				/*Initialize responses: */
-				responses=xNewZeroInit<IssmDouble>(numFns);
-
-				/*run core solution: */
-				DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
-
-				/*populate responses: */
-				for(i=0;i<numFns;i++){
-					fnVals[i]=responses[i];
-				}
-
-				/*Free ressources:*/
-				xDelete<IssmDouble>(variables);
-				for(i=0;i<numACV;i++){
-					variable_descriptor=variable_descriptors[i];
-					xDelete<char>(variable_descriptor);
-				}
-				xDelete<char*>(variable_descriptors);
-				xDelete<IssmDouble>(responses);
-
-				return 0;
-			}/*}}}*/
-			/*execute the output filter portion of a direct evaluation invocation*/
-			//int derived_map_of(const Dakota::String& of_name);
-			/*add for issm: */
-			int GetCounter(){/*{{{*/
-				return counter;
-			}/*}}}*/
-		private:
-	};
-} 
-#endif
-/*}}}*/
-
-void dakota_core(FemModel* femmodel){ 
-
-	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
-
-	int                my_rank;
-	char              *dakota_input_file  = NULL;
-	char              *dakota_output_file = NULL;
-	char              *dakota_error_file  = NULL;
-	int                status             = 0;
-	Dakota::ModelLIter ml_iter;
-	Parameters        *parameters         = NULL;
-
-	/*Recover dakota_input_file, dakota_output_file and dakota_error_file, in the parameters dataset in parallel */
-	femmodel->parameters->FindParam(&dakota_input_file,QmuInNameEnum);
-	femmodel->parameters->FindParam(&dakota_output_file,QmuOutNameEnum);
-	femmodel->parameters->FindParam(&dakota_error_file,QmuErrNameEnum);
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	if(my_rank==0){
-
-		// Instantiate/initialize the parallel library and problem description
-		// database objects.
-		char* dakotamode=xNew<char>(strlen("serial")+1);
-		xMemCpy<char>(dakotamode,"serial",strlen("serial")+1);
-		Dakota::ParallelLibrary parallel_lib(dakotamode); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
-		Dakota::ProblemDescDB problem_db(parallel_lib); 
-		xDelete<char>(dakotamode);
-
-		// Manage input file parsing, output redirection, and restart processing
-		// without a CommandLineHandler.  This version relies on parsing of an
-		// input file.
-		problem_db.manage_inputs(dakota_input_file);
-		// specify_outputs_restart() is only necessary if specifying non-defaults
-		parallel_lib.specify_outputs_restart(dakota_output_file,dakota_error_file,NULL,NULL);
-
-		// Instantiate the Strategy object (which instantiates all Model and
-		// Iterator objects) using the parsed information in problem_db.
-		Dakota::Strategy selected_strategy(problem_db);
-
-		// convenience function for iterating over models and performing any
-		// interface plug-ins
-		Dakota::ModelList& models = problem_db.model_list();
-
-		for (ml_iter = models.begin(); ml_iter != models.end(); ml_iter++) {
-
-			Dakota::Interface& interface = ml_iter->interface();
-
-			//set DB nodes to the existing Model specification
-			problem_db.set_db_model_nodes(ml_iter->model_id());
-
-			// Serial case: plug in derived Interface object without an analysisComm
-			interface.assign_rep(new SIM::DakotaPlugin(problem_db,(void*)femmodel), false);
-		}
-
-		// Execute the strategy
-		problem_db.lock(); // prevent run-time DB queries
-		selected_strategy.run_strategy();
-
-		//Warn other cpus that we are done running the dakota iterator, by setting the counter to -1:
-		DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,-1);
-
-	}
-	else{
-
-		for(;;){
-			if(!DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,0))break; //counter came in at -1 on cpu0, bail out.
-		}
-	}
-
-	/*Free ressources:*/
-	xDelete<char>(dakota_input_file);
-	xDelete<char>(dakota_error_file);
-	xDelete<char>(dakota_output_file);
-
-	#endif //#ifdef _HAVE_DAKOTA_
-}
Index: sm/trunk/src/c/analyses/dummy_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/dummy_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-/*!\file: dummy_core.cpp
- * \brief: dummy core (nothing done)
- */ 
-
-class FemModel;
-
-void dummy_core(FemModel* femmodel){
-
-	/*We do not do anything*/
-
-}
Index: sm/trunk/src/c/analyses/enthalpy_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/enthalpy_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,33 +1,0 @@
-/*!\file: enthalpy_core.cpp
- * \brief: core of the enthalpy solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../modules/modules.h"
-#include "../shared/shared.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void enthalpy_core(FemModel* femmodel){
-
-	/*intermediary*/
-	bool   save_results;
-
-	//first recover parameters common to all solutions
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("   computing enthalpy\n");
-	femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
-	solutionsequence_nonlinear(femmodel,true);
-
-	/*transfer enthalpy to enthalpy picard for the next step: */
-	InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum,EnthalpyPicardEnum);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,TemperatureEnum);
-		InputToResultx(femmodel,EnthalpyEnum);
-		InputToResultx(femmodel,WaterfractionEnum);
-	}
-}
Index: sm/trunk/src/c/analyses/gia_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/gia_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,57 +1,0 @@
-/*!\file: gia_core.cpp
- * \brief: core of the GIA solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-void gia_core(FemModel* femmodel){
-
-	int i;
-	Vector<IssmDouble>*  wg  = NULL;
-	Vector<IssmDouble>*  dwdtg  = NULL;
-	IssmDouble*          x   = NULL;
-	IssmDouble*          y   = NULL;
-
-	/*parameters: */
-	bool save_results;
-	int  gsize;
-	int  configuration_type;
-
-	/*Recover some parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-
-	if(VerboseSolution()) _printf0_("   computing GIA\n");
-
-	/*Call on core computations: */
-	femmodel->SetCurrentConfiguration(GiaAnalysisEnum);
-
-	/*Figure out size of g-set deflection vector and allocate solution vector: */
-	gsize      = femmodel->nodes->NumberOfDofs(configuration_type,GsetEnum);
-	wg = new Vector<IssmDouble>(gsize);
-	dwdtg = new Vector<IssmDouble>(gsize);
-
-	/*first, recover x and y vectors from vertices: */
-	VertexCoordinatesx(&x,&y,NULL,femmodel->vertices); //no need for z coordinate
-
-	/*call the main module: */
-	femmodel->Deflection(wg,dwdtg,x,y);
-
-	/*assemble vector: */
-	wg->Assemble();
-	dwdtg->Assemble();
-
-	InputUpdateFromVectorx(femmodel,wg,GiaWEnum,VertexSIdEnum);
-	InputUpdateFromVectorx(femmodel,dwdtg,GiadWdtEnum,VertexSIdEnum);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,GiaWEnum);
-		InputToResultx(femmodel,GiadWdtEnum);
-	}
-
-}
Index: sm/trunk/src/c/analyses/gradient_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/gradient_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,48 +1,0 @@
-/*!\file:  gradient_core.cpp
- * \brief compute inverse method gradient direction.
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void gradient_core(FemModel* femmodel,int step,bool orthogonalize){ 
-
-	/*Intermediaries*/
-	IssmDouble  norm_inf;
-	IssmDouble *norm_list    = NULL;
-	Vector<IssmDouble>*     new_gradient = NULL;
-	Vector<IssmDouble>*     gradient     = NULL;
-	Vector<IssmDouble>*     old_gradient = NULL;
-
-	/*Compute gradient*/
-	if(VerboseControl()) _printf0_("   compute cost function gradient\n");
-	Gradjx(&gradient,&norm_list,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
-
-	if (orthogonalize){
-		if(VerboseControl()) _printf0_("   orthogonalization\n");
-		ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
-		Orthx(&new_gradient,gradient,old_gradient); delete old_gradient; delete gradient;
-	}
-	else{ 
-		new_gradient=gradient;
-	}
-
-	/*Check that gradient is clean*/
-	norm_inf=new_gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
-
-	/*plug back into inputs: */
-	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,new_gradient);
-	delete new_gradient;
-
-	/*Scale Gradients*/
-	ControlInputScaleGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,norm_list,step);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(norm_list);
-}
Index: sm/trunk/src/c/analyses/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/hydrology_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,104 +1,0 @@
-/*!\file: hydrology_core.cpp
- * \brief: core of the hydrology solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void hydrology_core(FemModel* femmodel){
-
-	int i;
-
-	/*intermediary*/
-	int        step,nsteps;
-	int        output_frequency,hydrology_model;
-	bool       save_results;
-	bool       modify_loads=true;
-	bool       isefficientlayer;
-	IssmDouble starttime,final_time;
-	IssmDouble time,dt;
-
-	/*first recover parameters common to all solutions*/
-	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
-	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
-	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
-	femmodel->parameters->FindParam(&hydrology_model,HydrologyModelEnum);
-
-	/*first compute slopes: */
-	if (hydrology_model==HydrologyshreveEnum){
-		surfaceslope_core(femmodel);
-		bedslope_core(femmodel);
-	}
-
-	/*Compute number of time steps: */
-	if((dt==0)|| (final_time==0)){
-		dt=0;
-		nsteps=1;
-	}
-	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
-
-	/*initialize: */
-	step=0;
-	time=starttime;
-
-	/*Loop through time: */
-	for(i=0;i<nsteps;i++){
-
-		if(nsteps)if(VerboseSolution()) _printf0_("time step:" << i+1 << "/" << nsteps << "\n");
-		time+=dt;
-		step+=1;
-		femmodel->parameters->SetParam(time,TimeEnum);
-		femmodel->parameters->SetParam(step,StepEnum);
-
-		if (hydrology_model==HydrologyshreveEnum){
-			if(VerboseSolution()) _printf0_("   computing water column\n");
-			femmodel->SetCurrentConfiguration(HydrologyShreveAnalysisEnum);
-			solutionsequence_nonlinear(femmodel,modify_loads);
-
-			/*transfer water column thickness to old water column thickness: */
-
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,WaterColumnOldEnum);
-
-			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
-				if(VerboseSolution()) _printf0_("   saving results \n");
-				InputToResultx(femmodel,WatercolumnEnum);
-				InputToResultx(femmodel,HydrologyWaterVxEnum);
-				InputToResultx(femmodel,HydrologyWaterVyEnum);
-
-				/*unload results*/
-				if(VerboseSolution()) _printf0_("   saving temporary results\n");
-				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
-			}
-		}
-
-		else if (hydrology_model==HydrologydcEnum){
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SedimentHeadEnum,SedimentHeadOldEnum);
-			femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-			if (isefficientlayer){
-				InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EplHeadEnum,EplHeadOldEnum);
-			}
-
-			if(VerboseSolution()) _printf0_("   computing water head\n");
-			solutionsequence_hydro_nonlinear(femmodel);
-			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
-				if(VerboseSolution()) _printf0_("   saving results \n");
-				InputToResultx(femmodel,SedimentHeadEnum);
-				InputToResultx(femmodel,SedimentHeadResidualEnum);
-				if(isefficientlayer){
-					InputToResultx(femmodel,EplHeadEnum);
-					InputToResultx(femmodel,HydrologydcMaskEplactiveEnum);
-				}
-				/*unload results*/
-				if(VerboseSolution()) _printf0_("   saving temporary results\n");
-				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
-			}
-		}
-
-	}
-}
Index: sm/trunk/src/c/analyses/masstransport_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/masstransport_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,72 +1,0 @@
-/*!\file: masstransport_core.cpp
- * \brief: core of the masstransport solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void masstransport_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool  save_results;
-	bool  issmbgradients,ispdd,isdelta18o,isFS,isfreesurface;
-	int   solution_type;
-	int  *requested_outputs = NULL;
-	int   numoutputs        = 0;
-
-	/*activate configuration*/
-	femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
-
-	/*recover parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
-	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
-	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
-	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&isfreesurface,MasstransportIsfreesurfaceEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
-
-	if(issmbgradients){
-	  if(VerboseSolution())_printf_("	call smb gradients module\n\n");
-	  SmbGradientsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-	if(ispdd){
-		if(isdelta18o){
-			if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
-			Delta18oParameterizationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-		} 
-		if(VerboseSolution()) _printf0_("   call positive degree day module\n");
-		PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-
-	if(isFS && isfreesurface){
-		if(VerboseSolution()) _printf0_("   call free surface computational core\n");
-		femmodel->SetCurrentConfiguration(FreeSurfaceBaseAnalysisEnum);
-		solutionsequence_linear(femmodel);
-		femmodel->SetCurrentConfiguration(FreeSurfaceTopAnalysisEnum);
-		solutionsequence_linear(femmodel);
-	}
-	else{
-		if(VerboseSolution()) _printf0_("   call computational core\n");
-		solutionsequence_linear(femmodel);
-	}
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,ThicknessEnum);
-		InputToResultx(femmodel,BedEnum);
-		InputToResultx(femmodel,SurfaceEnum);
-		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-	}
-
-	if(solution_type==MasstransportSolutionEnum)femmodel->RequestedDependentsx();
-
-	/*Free ressources:*/
-	xDelete<int>(requested_outputs);
-}
Index: sm/trunk/src/c/analyses/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/analyses/objectivefunction.cpp	(revision 16559)
+++ 	(revision )
@@ -1,77 +1,0 @@
-/*!\file:  objectivefunction
- * \brief  objective function that returns a misfit, for a certain parameter.
- */ 
-
-/*include files: {{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../solutionsequences/solutionsequences.h"
-#include "../modules/modules.h"
-/*}}}*/
-
-IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
-
-	/*output: */
-	IssmDouble J;
-
-	/*parameters: */
-	int        solution_type,analysis_type;
-	bool       isFS       = false;
-	bool       conserve_loads = true;
-	FemModel  *femmodel       = NULL;
-
-	/*Recover finite element model: */
-	femmodel=optargs->femmodel;
-
-	/*Recover parameters: */
-	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-
-	/*set analysis type to compute velocity: */
-	if (solution_type==SteadystateSolutionEnum || solution_type==StressbalanceSolutionEnum){
-		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-	}
-	else if (solution_type==BalancethicknessSolutionEnum){
-		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	}
-	else if (solution_type==BalancethicknessSoftSolutionEnum){
-		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	}
-	else{
-		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
-	}
-
-	/*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 stressbalance with updated inputs: */
-	if (solution_type==SteadystateSolutionEnum){
-		stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
-	}
-	else if (solution_type==StressbalanceSolutionEnum){
-		solutionsequence_nonlinear(femmodel,conserve_loads); 
-	}
-	else if (solution_type==BalancethicknessSolutionEnum){
-		solutionsequence_linear(femmodel); 
-	}
-	else if (solution_type==BalancethicknessSoftSolutionEnum){
-		/*Don't do anything*/
-	}
-	else{
-		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
-	}
-
-	/*Compute misfit for this velocity field.*/
-	femmodel->CostFunctionx(&J);
-
-	/*Free ressources:*/
-	return J;
-}
Index: sm/trunk/src/c/analyses/steadystate_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/steadystate_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,146 +1,0 @@
-/*!\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 "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-/*Local prototypes*/
-bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol);
-
-void steadystate_core(FemModel* femmodel){
-
-	/*intermediary: */
-	int step; 
-	Vector<IssmDouble>* ug     = NULL;
-	Vector<IssmDouble>* ug_old = NULL;
-	Vector<IssmDouble>* tg     = NULL;
-	Vector<IssmDouble>* tg_old = NULL;
-
-	/*parameters: */
-	bool        save_results,isenthalpy;
-	int         maxiter;
-	IssmDouble  reltol;
-	int         numoutputs        = 0;
-	int        *requested_outputs = NULL;
-
-	/* recover parameters:*/
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&maxiter,SteadystateMaxiterEnum);
-	femmodel->parameters->FindParam(&numoutputs,SteadystateNumRequestedOutputsEnum);
-	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
-	femmodel->parameters->FindParam(&reltol,SteadystateReltolEnum);
-	femmodel->parameters->SetParam(false,SaveResultsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,SteadystateRequestedOutputsEnum);
-
-	/*intialize counters: */
-	step=1;
-
-	for(;;){
-
-		if(VerboseSolution()) _printf0_("   computing temperature and velocity for step: " << step << "\n");
-		#ifdef _HAVE_THERMAL_
-		if(isenthalpy==0){
-			thermal_core(femmodel);
-			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-			GetSolutionFromInputsx(&tg,femmodel);
-		}
-		else{
-			enthalpy_core(femmodel);
-			GetSolutionFromInputsx(&tg,femmodel);
-		}
-		#else
-		_error_("ISSM was not compiled with thermal capabilities. Exiting");
-		#endif
-
-		if(VerboseSolution()) _printf0_("   computing new velocity\n");
-		stressbalance_core(femmodel);
-		GetSolutionFromInputsx(&ug,femmodel);
-
-		if(step>1){
-			if(VerboseSolution()) _printf0_("   checking steadystate convergence\n");
-			if(steadystateconvergence(tg,tg_old,ug,ug_old,reltol)) break;
-		}
-		if(step>maxiter){
-			if(VerboseSolution()) _printf0_("   maximum number steadystate iterations " << maxiter << " reached\n");
-			break;
-		}
-
-		/*update results and increase counter*/
-		delete tg_old;tg_old=tg;
-		delete ug_old;ug_old=ug;
-		step++;
-	}
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,VxEnum);
-		InputToResultx(femmodel,VyEnum);
-		InputToResultx(femmodel,VzEnum);
-		InputToResultx(femmodel,VelEnum);
-		InputToResultx(femmodel,PressureEnum);
-		InputToResultx(femmodel,TemperatureEnum);
-		if(isenthalpy)  InputToResultx(femmodel,WaterfractionEnum);
-		if(isenthalpy)  InputToResultx(femmodel,EnthalpyEnum);
-        	if(isenthalpy)  InputToResultx(femmodel,WatercolumnEnum);
-		//if(!isenthalpy) InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
-        	InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
-		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-	}
-
-	/*Free ressources:*/
-	delete tg_old;
-	delete ug_old;
-	delete tg;
-	delete ug;
-	xDelete<int>(requested_outputs);
-}
-bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol){
-
-	/*Output*/
-	bool converged = true;
-
-	/*Intermediary*/
-	Vector<IssmDouble>* dug    = NULL;
-	Vector<IssmDouble>* dtg    = NULL;
-	IssmDouble          ndt,nt;
-	IssmDouble          ndu,nu;
-
-	/*compute norm(du)/norm(u)*/
-	dug=ug_old->Duplicate(); ug_old->Copy(dug); dug->AYPX(ug,-1.0);
-	ndu=dug->Norm(NORM_TWO); nu=ug_old->Norm(NORM_TWO);
-	if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
-	if((ndu/nu)<reltol){
-		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" < "<<reltol*100<<" %\n");
-	}
-	else{ 
-		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" > "<<reltol*100<<" %\n");
-		converged=false;
-	}
-
-	/*compute norm(dt)/norm(t)*/
-	dtg=tg_old->Duplicate(); tg_old->Copy(dtg); dtg->AYPX(tg,-1.0);
-	ndt=dtg->Norm(NORM_TWO); nt=tg_old->Norm(NORM_TWO);
-	if (xIsNan<IssmDouble>(ndt) || xIsNan<IssmDouble>(nt)) _error_("convergence criterion is NaN!");
-	if((ndt/nt)<reltol){
-		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" < "<<reltol*100<<" %\n");
-	}
-	else{ 
-		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" > "<<reltol*100<<" %\n");
-		converged=false;
-	}
-
-	/*clean up and return*/
-	delete dtg;
-	delete dug;
-	return converged;
-}
Index: sm/trunk/src/c/analyses/stressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/stressbalance_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,100 +1,0 @@
-/*!\file: stressbalance_core.cpp
- * \brief: core of the stressbalance solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void stressbalance_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool  dakota_analysis;
-	int   dim;
-	bool  isSIA,isSSA,isL1L2,isHO,isFS;
-	bool  conserve_loads    = true;
-	bool  save_results;
-	int   newton;
-	int   solution_type;
-	int   numoutputs        = 0;
-	int  *requested_outputs = NULL;
-
-	/* recover parameters:*/
-	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
-	femmodel->parameters->FindParam(&isSIA,FlowequationIsSIAEnum);
-	femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
-	femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
-	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
-	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis && solution_type==StressbalanceSolutionEnum){
-		InputDuplicatex(femmodel->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(isSIA) surfaceslope_core(femmodel);
-	if(isFS){
-		bedslope_core(femmodel);
-		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-		ResetCoordinateSystemx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-
-	if(isSIA){
-		if(VerboseSolution()) _printf0_("   computing SIA velocities\n");
-
-		/*Take the last velocity into account so that the velocity on the SSA domain is not zero*/
-		if(isSSA || isL1L2 || isHO ) ResetBoundaryConditions(femmodel,StressbalanceSIAAnalysisEnum);
-		femmodel->SetCurrentConfiguration(StressbalanceSIAAnalysisEnum);
-		solutionsequence_linear(femmodel);
-		if(isSSA || isL1L2 || isHO) ResetBoundaryConditions(femmodel,StressbalanceAnalysisEnum);
-	}
-
-	if ((isSSA || isHO || isL1L2) ^ isFS){ // ^ = xor
-		if(VerboseSolution()) _printf0_("   computing velocities\n");
-
-		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-		if(newton>0)
-		 solutionsequence_newton(femmodel);
-		else
-		 solutionsequence_nonlinear(femmodel,conserve_loads); 
-	}
-
-	if ((isSSA || isL1L2 || isHO) && isFS){
-		if(VerboseSolution()) _printf0_("   computing coupling betweem lower order models and full-FS\n");
-		solutionsequence_FScoupling_nonlinear(femmodel,conserve_loads);
-	}
-
-	if (dim==3 & (isSIA || isSSA || isL1L2 || isHO)){
-		if(VerboseSolution()) _printf0_("   computing vertical velocities\n");
-		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
-		solutionsequence_linear(femmodel);
-	}
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,VxEnum);
-		InputToResultx(femmodel,VyEnum);
-		InputToResultx(femmodel,VelEnum);
-		InputToResultx(femmodel,PressureEnum);
-		if(dim==3) InputToResultx(femmodel,VzEnum);
-		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-	}
-
-	if(solution_type==StressbalanceSolutionEnum)femmodel->RequestedDependentsx();
-
-	/*Free ressources:*/
-	xDelete<int>(requested_outputs);
-}
Index: sm/trunk/src/c/analyses/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/surfaceslope_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,34 +1,0 @@
-/*!\file: surfaceslope_core.cpp
- * \brief: core of the slope solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../solutionsequences/solutionsequences.h"
-#include "../modules/modules.h"
-
-void surfaceslope_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-	/*Recover some parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("computing slope...\n");
-
-	/*Call on core computations: */
-	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeXAnalysisEnum);
-	solutionsequence_linear(femmodel);
-	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("saving results:\n");
-		InputToResultx(femmodel,SurfaceSlopeXEnum);
-		InputToResultx(femmodel,SurfaceSlopeYEnum);
-	}
-
-}
Index: sm/trunk/src/c/analyses/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/thermal_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,45 +1,0 @@
-/*!\file: thermal_core.cpp
- * \brief: core of the thermal solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void thermal_core(FemModel* femmodel){
-
-	/*intermediary*/
-	bool   save_results;
-	bool   dakota_analysis  = false;
-	int    solution_type;
-
-	//first recover parameters common to all solutions
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-
-	if(dakota_analysis && solution_type!=TransientSolutionEnum){
-		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-		ResetConstraintsx(femmodel);
-	}
-
-	if(VerboseSolution()) _printf0_("   setting basal Dirichlet boundary conditions\n");
-	femmodel->UpdateThermalBasalConstraintsx();
-
-	if(VerboseSolution()) _printf0_("   computing temperatures\n");
-	femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-	solutionsequence_thermal_nonlinear(femmodel);
-
-	if(VerboseSolution()) _printf0_("   computing melting\n");
-	femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel,TemperatureEnum);
-		InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
-	}
-}
Index: sm/trunk/src/c/analyses/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/transient_core.cpp	(revision 16559)
+++ 	(revision )
@@ -1,180 +1,0 @@
-/*!\file: transient_3d_core.cpp
- * \brief: core of the transient_3d solution 
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <float.h>
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void transient_core(FemModel* femmodel){
-
-	/*parameters: */
-	IssmDouble starttime,finaltime,dt,yts;
-	bool   isstressbalance,ismasstransport,isthermal,isgroundingline,isenthalpy,isdelta18o,isgia;
-	bool   save_results,dakota_analysis;
-	bool   time_adapt=false;
-	int    output_frequency;
-	int    dim,groundingline_migration;
-	int    numoutputs         = 0;
-	int    *requested_outputs = NULL;
-
-	/*intermediary: */
-	int    step;
-	IssmDouble time;
-
-	//first recover parameters common to all solutions
-	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
-	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
-	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
-	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
-	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
-	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
-	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
-	femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
-	femmodel->parameters->FindParam(&isgia,TransientIsgiaEnum);
-	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
-	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
-	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
-	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
-	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
-
-	/*initialize: */
-	step=0;
-	time=starttime;
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis){
-		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(dim==2)InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-		if(isthermal && dim==3){
-			//Update Vertex Position after updating Thickness and Bed
-			femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
-			femmodel->UpdateVertexPositionsx();
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxMeshEnum,VxMeshEnum);
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyMeshEnum,VyMeshEnum);
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzMeshEnum,VzMeshEnum);
-			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);
-			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
-			//Reset Thermal Constraints
-			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-			ResetConstraintsx(femmodel);
-		}
-	}
-
-	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
-
-		/*Increment*/
-		if(time_adapt){
-			femmodel->TimeAdaptx(&dt);
-			if(time+dt>finaltime) dt=finaltime-time;
-			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
-		}
-		step+=1;
-		time+=dt;
-		femmodel->parameters->SetParam(time,TimeEnum);
-		femmodel->parameters->SetParam(step,StepEnum);
-
-		if(VerboseSolution()) _printf0_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << time/yts << " (time step: " << dt/yts << ")\n");
-		if(step%output_frequency==0 || time==finaltime)
-		 save_results=true;
-		else
-		 save_results=false;
-		femmodel->parameters->SetParam(save_results,SaveResultsEnum);
-
-		if(isthermal && dim==3){
-			if(VerboseSolution()) _printf0_("   computing temperatures\n");
-			#ifdef _HAVE_THERMAL_
-			if(isenthalpy==0){
-				thermal_core(femmodel);
-			}
-			else{
-				enthalpy_core(femmodel);
-                		PostprocessingEnthalpyx(femmodel);
-			}
-			#else
-			_error_("ISSM was not compiled with thermal capabilities. Exiting");
-			#endif
-		}
-
-		if(isstressbalance){
-			if(VerboseSolution()) _printf0_("   computing new velocity\n");
-			#ifdef _HAVE_STRESSBALANCE_
-			stressbalance_core(femmodel);
-			#else
-			_error_("ISSM was not compiled with stressbalance capabilities. Exiting");
-			#endif
-		}
-
-		if(ismasstransport){
-			if(VerboseSolution()) _printf0_("   computing new thickness\n");
-			masstransport_core(femmodel);
-			if(VerboseSolution()) _printf0_("   updating vertices positions\n");
-			femmodel->UpdateVertexPositionsx();
-		}
-
-		if(isgroundingline){
-			if(VerboseSolution()) _printf0_("   computing new grounding line position\n");
-			#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
-			if(save_results){
-				InputToResultx(femmodel,SurfaceEnum);
-				InputToResultx(femmodel,BedEnum);
-				InputToResultx(femmodel,MaskGroundediceLevelsetEnum);
-			}
-		}
-		if(isgia){
-			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
-			#ifdef _HAVE_GIA_
-			gia_core(femmodel);
-			#else
-			_error_("ISSM was not compiled with gia capabilities. Exiting");
-			#endif
-
-		}
-
-		/*unload results*/
-		if(save_results){
-			if(VerboseSolution()) _printf0_("   saving transient results\n");
-			InputToResultx(femmodel,SurfaceforcingsMassBalanceEnum);
-			femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-			if(isdelta18o){
-				InputToResultx(femmodel,SurfaceforcingsMonthlytemperaturesEnum);
-				InputToResultx(femmodel,SurfaceforcingsPrecipitationEnum);
-			}
-			if(isgroundingline && (groundingline_migration==SubelementMigrationEnum || groundingline_migration==SubelementMigration2Enum)){
-				InputToResultx(femmodel,MaskGroundediceLevelsetEnum);
-			}
-			if(VerboseSolution()) _printf0_("   saving temporary results\n");
-			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
-		}
-	}
-
-	femmodel->RequestedDependentsx();
-
-	/*Free ressources:*/
-	xDelete<int>(requested_outputs);
-}
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 16560)
@@ -16,9 +16,4 @@
 	int  AdjacentTriangle::Locked() const {
 		return t->AdjEdgeIndex[a] & 4;
-	}
-	/*}}}*/
-	/*FUNCTION AdjacentTriangle::MarkUnSwap {{{*/
-	int  AdjacentTriangle::MarkUnSwap() const {
-		return t->AdjEdgeIndex[a] & 8;
 	}
 	/*}}}*/
@@ -42,9 +37,4 @@
 	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {
 		return t->vertices[VerticesOfTriangularEdge[a][i]];
-	}
-	/*}}}*/
-	/*FUNCTION AdjacentTriangle::OppositeVertex {{{*/
-	BamgVertex* AdjacentTriangle::OppositeVertex() const {
-		return t->vertices[bamg::OppositeVertex[a]]; 
 	}
 	/*}}}*/
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 16560)
@@ -31,5 +31,4 @@
 			//Methods
 			int  Locked() const;
-			int  MarkUnSwap() const;
 			int  GetAllFlag_UnSwap() const;
 			void SetLock();
@@ -38,5 +37,4 @@
 			AdjacentTriangle Adj() const;
 			BamgVertex* EdgeVertex(const int & i) const;
-			BamgVertex* OppositeVertex() const;
 			Icoor2& det() const;
 	};
Index: /issm/trunk/src/c/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 16560)
@@ -350,5 +350,5 @@
 
 					/*if the next box exists:*/
-					if (b=b->b[k]){
+					if((b=b->b[k])){
 
 						/*Get size (hb) and coordinates of the current sub-box lowest left corner*/
@@ -391,111 +391,4 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgQuadtree::NearestVertexWithNormal{{{*/
-	BamgVertex*  BamgQuadtree::NearestVertexWithNormal(Icoor1 i,Icoor1 j) {
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/NearestVertexWithNormal)*/
-
-		BamgQuadtreeBox * pb[ MaxDepth ];
-		int  pi[ MaxDepth  ];
-		Icoor1 ii[  MaxDepth ], jj [ MaxDepth];
-		int l; // level
-		BamgQuadtreeBox * b;
-		long     h =MaxISize,h0;
-		long     hb=MaxISize;
-		Icoor1  i0=0,j0=0;
-		Icoor1  iplus( i<MaxISize?(i<0?0:i):MaxISize-1);
-		Icoor1  jplus( j<MaxISize?(j<0?0:j):MaxISize-1);
-
-		BamgVertex *vn=0;
-
-		// init for optimisation ---
-		b = root;
-		register long  n0;
-		if (!root->nbitems)
-		 return vn; // empty tree 
-
-		while( (n0 = b->nbitems) < 0) 
-		  {
-			// search the non empty 
-			// BamgQuadtreeBox containing  the point (i,j)
-			register Icoor1 hb2 = hb >> 1 ;
-			register  int k = IJ(iplus,jplus,hb2);// BamgQuadtreeBox number of size hb2 contening i;j
-			register BamgQuadtreeBox * b0= b->b[k];
-			if ( ( b0 == 0) || (b0->nbitems == 0) ) 
-			 break; // null box or empty   => break 	    
-			b=b0;	
-			i0 += I_IJ(k,hb2); // i orign of BamgQuadtreeBox
-			j0 += J_IJ(k,hb2); // j orign of BamgQuadtreeBox 
-			hb = hb2; 
-		  }
-
-		if ( n0 > 0) 
-		  {  
-			for(register int k=0;k<n0;k++)
-			  {
-				I2 i2 =  b->v[k]->i;
-				//   try if is in the right direction -- 
-				h0 = NORM(iplus,i2.x,jplus,i2.y);
-				if (h0 <h) {
-					h = h0;
-					vn = b->v[k];}
-			  }
-			if (vn) return vn; 
-		  }
-		// general case -----
-		// INITIALISATION OF THE HEAP 
-		l =0; // level 
-		pb[0]= b;
-		pi[0]=b->nbitems>0 ?(int)  b->nbitems : 4  ;
-		ii[0]=i0;
-		jj[0]=j0;
-		h=hb;
-		do {   // walk on the tree  
-			b= pb[l];
-			while (pi[l]--) // loop on 4 element of the box
-			  { 	      
-				int k = pi[l];
-
-				if (b->nbitems>0) // BamgVertex BamgQuadtreeBox none empty
-				  { 
-					I2 i2 =  b->v[k]->i;
-					// if good direction when try -- 
-
-					h0 = NORM(iplus,i2.x,jplus,i2.y);
-					if (h0 <h) 
-					  {
-						h = h0;
-						vn = b->v[k];
-					  }
-				  }
-				else // Pointer BamgQuadtreeBox 
-				  { 
-					register BamgQuadtreeBox *b0=b;
-					if ((b=b->b[k])) 
-					  {
-						hb >>=1 ; // div by 2
-						register Icoor1 iii = ii[l]+I_IJ(k,hb);
-						register Icoor1 jjj = jj[l]+J_IJ(k,hb);
-
-						if  (INTER_SEG(iii,iii+hb,iplus-h,iplus+h) && INTER_SEG(jjj,jjj+hb,jplus-h,jplus+h)) 
-						  {
-							pb[++l]=  b;
-							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
-							ii[l]= iii;
-							jj[l]= jjj;
-
-						  }
-						else
-						 b=b0, hb <<=1 ;
-					  }
-					else
-					 b=b0;
-				  }
-			  }
-			hb <<= 1; // mul by 2 
-		} while (l--);
-
-		return vn;
-	}
-	/*}}}*/
 	/*FUNCTION BamgQuadtree::NewBamgQuadtreeBox {{{*/
 	BamgQuadtree::BamgQuadtreeBox* BamgQuadtree::NewBamgQuadtreeBox(void){
@@ -535,5 +428,4 @@
 		register int l=0; // level
 		register BamgQuadtreeBox * b;
-		Icoor1 h=MaxISize;
 		Icoor1 hb =  MaxISize;
 		Icoor1 i0=0,j0=0;
@@ -549,5 +441,4 @@
 		ii[0]=i0;
 		jj[0]=j0;
-		h=hb;
 		do {    
 			b= pb[l];
@@ -560,6 +451,5 @@
 					  {
 						R2 XY(X,b->v[k]->r);
-						double dd;
-						if( (dd= LengthInterpole(Mx(XY), b->v[k]->m(XY)))  < seuil ){
+						if(LengthInterpole(Mx(XY), b->v[k]->m(XY)) < seuil){
 							return b->v[k]; 
 						}
Index: /issm/trunk/src/c/bamg/BamgQuadtree.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgQuadtree.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/BamgQuadtree.h	(revision 16560)
@@ -52,5 +52,4 @@
 
 			BamgVertex      *NearestVertex(Icoor1 i,Icoor1 j);
-			BamgVertex      *NearestVertexWithNormal(Icoor1  i,Icoor1 j);
 			BamgQuadtreeBox *NewBamgQuadtreeBox(void);
 			BamgVertex      *ToClose(BamgVertex &,double ,Icoor1,Icoor1);
Index: /issm/trunk/src/c/bamg/Curve.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Curve.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/Curve.cpp	(revision 16560)
@@ -20,11 +20,4 @@
 
 	/*Methods*/
-	/*FUNCTION Curve::Reverse {{{*/
-	void Curve::Reverse() {
-		/*reverse the direction of the curve */
-		Exchange(FirstEdge,LastEdge);
-		Exchange(FirstVertexIndex,LastVertexIndex);
-	}
-	/*}}}*/
 	/*FUNCTION Curve::Set {{{*/
 	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){
Index: /issm/trunk/src/c/bamg/Curve.h
===================================================================
--- /issm/trunk/src/c/bamg/Curve.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/Curve.h	(revision 16560)
@@ -19,5 +19,4 @@
 			//Methods
 			Curve();
-			void Reverse(void);
 			void Set(const Curve & rec,const Geometry & Th ,Geometry & ThNew);
 	};
Index: /issm/trunk/src/c/bamg/Direction.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Direction.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/Direction.cpp	(revision 16560)
@@ -27,5 +27,5 @@
 		int r =1; 
 		if (dir!= MaxICoor) {
-			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y(dir%2?-y1:y1);
+			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y((dir%2)?-y1:y1);
 			r = (x*i + y*j) >=0;
 		}
Index: /issm/trunk/src/c/bamg/EigenMetric.cpp
===================================================================
--- /issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 16560)
@@ -99,15 +99,7 @@
 		lambda1=bamg::Abs(lambda1),lambda2=bamg::Abs(lambda2);
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Aniso{{{*/
-	double EigenMetric::Aniso() const  { 
-		return sqrt( Aniso2());
-	}/*}}}*/
 	/*FUNCTION EigenMetric::Aniso2{{{*/
 	double EigenMetric::Aniso2() const  { 
 		return lmax()/lmin();
-	}/*}}}*/
-	/*FUNCTION EigenMetric::BoundAniso{{{*/
-	void   EigenMetric::BoundAniso(const double c){ 
-		BoundAniso2(1/(c*c));
 	}/*}}}*/
 	/*FUNCTION EigenMetric::Echo {{{*/
@@ -130,8 +122,4 @@
 	double EigenMetric::hmax() const {
 		return sqrt(1/bamg::Max(bamg::Min(lambda1,lambda2),1e-30));
-	}/*}}}*/
-	/*FUNCTION EigenMetric::Isotrope{{{*/
-	void   EigenMetric::Isotrope() {
-		lambda1=lambda2=bamg::Max(lambda1,lambda2);
 	}/*}}}*/
 	/*FUNCTION EigenMetric::lmax{{{*/
Index: /issm/trunk/src/c/bamg/GeomEdge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 16560)
@@ -175,8 +175,4 @@
 		type |= 64;/*=>6th digit to 1*/ 
 	}/*}}}*/
-	  /*FUNCTION GeomEdge::Tg{{{*/
-	int    GeomEdge::Tg(int i) const  {
-		return i==0 ? TgA() : TgB();
-	}/*}}}*/
 	/*FUNCTION GeomEdge::TgA{{{*/
 	int    GeomEdge::TgA()     const  {
Index: /issm/trunk/src/c/bamg/GeomEdge.h
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/GeomEdge.h	(revision 16560)
@@ -28,5 +28,4 @@
 			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;
Index: /issm/trunk/src/c/bamg/Geometry.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/Geometry.cpp	(revision 16560)
@@ -62,6 +62,4 @@
 
 		int verbose;
-		nbv=0;
-		nbe=0;
 		nbcurves=0;
 
@@ -286,5 +284,4 @@
 		int nbreqv=0;
 		int nbtan=0;
-		int nbcracked=0;
 		int i,count;
 
@@ -378,5 +375,4 @@
 		if (nbtan){
 			bamggeom->TangentAtEdges=xNew<double>(4*nbtan);
-			count=0;
 			for (i=0;i<nbe;i++){
 				if (edges[i].TgA() && edges[i][0].Corner()){
@@ -392,5 +388,4 @@
 					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[1].y;
 				}
-				count=count+1;
 			}
 		}
@@ -468,30 +463,4 @@
 		return c - curves;
 	}/*}}}*/
-	/*FUNCTION Geometry::Containing{{{*/
-	GeomEdge* Geometry::Containing(const R2 P,  GeomEdge * start) const {
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Contening)*/
-
-		GeomEdge* on =start,* pon=0;
-		// walk with the cos on geometry
-		int counter=0;
-		while(pon != on){  
-			counter++;
-			_assert_(counter<100);
-			pon = on;
-			R2 A= (*on)[0];
-			R2 B= (*on)[1];
-			R2 AB = B-A;
-			R2 AP = P-A;
-			R2 BP = P-B;
-			if ( (AB,AP) < 0) 
-			 on = on->Adj[0];
-			else if ( (AB,BP)  > 0) 
-			 on = on->Adj[1];
-			else
-			 return on;
-		}
-		return on;
-	}
-	/*}}}*/
 	/*FUNCTION Geometry::PostRead{{{*/
 	void Geometry::PostRead(){
@@ -504,5 +473,4 @@
 		double        eps      = 1e-20;
 		BamgQuadtree  quadtree;                            // build quadtree to find duplicates
-		BamgVertex   *v0       = vertices;
 
 		k=0;
Index: /issm/trunk/src/c/bamg/Geometry.h
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/Geometry.h	(revision 16560)
@@ -60,6 +60,5 @@
 			long             GetId(const Curve *c) const;
 			void             UnMarkEdges();
-			GeomEdge *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
-			GeomEdge *Containing(const R2 P, GeomEdge *start) const;
+			GeomEdge        *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
 			void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
 	};
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 16560)
@@ -48,5 +48,4 @@
 
 		SegInterpolation* SegI=lSegsI;
-		SegI=lSegsI;
 		lSegsI[NbSeg].last=Size;
 		int EndSeg=Size;
@@ -181,26 +180,4 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::NewSubSeg{{{*/
-	void  ListofIntersectionTriangles::NewSubSeg(GeomEdge *e,double s0,double s1){ 
-		long int verbosity=0;
-		if (NbSeg>=MaxNbSeg) {
-			int mneo= MaxNbSeg;
-			MaxNbSeg *= 2;
-			if (verbosity>3){
-				_printf_("   reshape lSegsI from " << mneo << " to " << MaxNbSeg << "\n");
-			}
-			_assert_(lSegsI && NbSeg<MaxNbSeg);
-			SegInterpolation * lEn =  new SegInterpolation[MaxNbSeg];
-			for (int i=0;i< NbSeg;i++) lEn[i] = lSegsI[MaxNbSeg]; // copy old to new            
-			delete []  lSegsI; // remove old
-			lSegsI = lEn;        
-		}
-		if (NbSeg) lSegsI[NbSeg-1].last=Size;
-		lSegsI[NbSeg].e=e;
-		lSegsI[NbSeg].sBegin=s0;
-		lSegsI[NbSeg].sEnd=s1;     
-		NbSeg++;           
-	}
-	/*}}}*/
 	/*FUNCTION ListofIntersectionTriangles::ReShape{{{*/
 	void ListofIntersectionTriangles::ReShape(){ 
@@ -225,8 +202,7 @@
 		Triangle *tbegin, *t;
 
-		long int verbose=2;
 		Icoor2 deta[3], deti,detj;
 		double ba[3];
-		int nbt =0,ifirst=-1,ilast;
+		int ifirst=-1,ilast;
 		int i0,i1,i2;
 		int ocut,i,j,k=-1;
@@ -288,5 +264,4 @@
 				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);
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 16560)
@@ -66,5 +66,4 @@
 			double Length();
 			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
-			void   NewSubSeg(GeomEdge *e,double s0,double s1);
 			void   ReShape();
 	};
Index: /issm/trunk/src/c/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/Mesh.cpp	(revision 16560)
@@ -122,15 +122,15 @@
 		  }
 		  for (i=0;i<Tho.nbt;i++)
-			if(  reft[i] >=0 && flag[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){
+				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){
+				if(i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					delete [] refv;
 					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
 				}
@@ -139,7 +139,4 @@
 				nbt++;           
 			  }
-		  if (kt!=nbt){
-			  _error_("kt!=nbt");
-		  }
 		  if (nbt==0 && nbv==0) {
 			  _error_("All triangles have been removed");
@@ -148,5 +145,4 @@
 		  delete [] reft;
 		  delete [] refv;
-		  //double cutoffradian = 10.0/180.0*Pi;
 		  BuildGeometryFromMesh(bamgopts);
 		  Gh.PostRead(); 
@@ -154,11 +150,8 @@
 		  ReconstructExistingMesh();
 
-		  if (!nbsubdomains){
-			  _error_("nbsubdomains==0");
-		  }
-		  if (!subdomains[0].head || !subdomains[0].head->link){
-			  _error_("!subdomains[0].head || !subdomains[0].head->link");
-		  }
-
+		  /*Final checks*/
+		  _assert_(kt==nbt);
+		  _assert_(nbsubdomains);
+		  _assert_(subdomains[0].head && subdomains[0].head->link); 
 	  }
 	/*}}}*/
@@ -269,5 +262,4 @@
 	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){
 
-		double Hmin = HUGE_VAL;// the infinie value 
 		long i1,i2,i3;
 		long i;
@@ -523,7 +515,9 @@
 				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 (i3!=3) _error_("Bad Subdomain definition: first number should be 3");
 				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
 				subdomains[i].head = triangles+head;
+				subdomains[i].direction = direction;
+				subdomains[i].ReferenceNumber = i3;
 			}
 		}
@@ -1030,4 +1024,5 @@
 				Triangle &t=triangles[i];
 				if (t.det>0 && !(t.Hidden(0)||t.Hidden(1) || t.Hidden(2) )){
+					/*Remove triangles that have a bad aspect ratio*/
 					//if(t.Anisotropy()<2 & t.Length()<1.e+5){
 						index[num*3+0]=GetId(t[0])+1; //back to M indexing
@@ -1052,7 +1047,6 @@
 
 		/*Get options*/
-		int    verbose=bamgopts->verbose;
-		double anisomax =bamgopts->anisomax;
-		double errg     =bamgopts->errg;
+		double anisomax = bamgopts->anisomax;
+		double errg     = bamgopts->errg;
 
 		double ss[2]={0.00001,0.99999};
@@ -1062,10 +1056,8 @@
 
 		//check that hmax is positive
-		if (hmax<=0){
-			_error_("hmax<=0");
-		}
+		_assert_(hmax>0); 
 
 		//errC cannot be higher than 1
-		if (errC>1) errC=1;
+		if(errC>1) errC=1;
 
 		//Set all vertices to "on"
@@ -1073,5 +1065,5 @@
 
 		//loop over all the vertices on edges
-		for (int  i=0;i<nbe;i++){
+		for(int  i=0;i<nbe;i++){
 			for (int j=0;j<2;j++){
 
@@ -1160,5 +1152,5 @@
 
 		//some checks
-		if (( infvertexindex <0 ) && (detOld <0) ||  ( infvertexindex >=0  ) && (detOld >0) ){
+		if(((infvertexindex <0 ) && (detOld <0)) ||  ((infvertexindex >=0) && (detOld >0)) ){
 			_error_("inconsistent configuration (Contact ISSM developers)");
 		}
@@ -1727,14 +1719,11 @@
 			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");
-		  }
+			_assert_(k>=0);
+			subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
+			subdomains[i].edge = edges+k;
+			Gh.subdomains[i].edge = Gh.edges + k;
+			Gh.subdomains[i].direction  =  subdomains[i].direction;
+			Gh.subdomains[i].ReferenceNumber =  subdomains[i].ReferenceNumber;
+		}
 
 		delete edge4;
@@ -2187,8 +2176,10 @@
 				// 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];
+					if      (xy==0) dd=dxdx;
+					else if (xy==1) dd=dxdy;
+					else if (xy==2) dd=dydy;
+					else    _error_("not supported yet");
 					// do leat 2 iteration for boundary problem
 					for (int ijacobi=0;ijacobi<Max(NbJacobi,2);ijacobi++){
@@ -2620,6 +2611,5 @@
 
 			  }
-			else
-			  { // find the head for all sub domaine
+			else{ // find the head for all subdomains
 				if (Gh.nbsubdomains != nbsubdomains && subdomains)
 				 delete [] subdomains, subdomains=0;
@@ -2627,5 +2617,4 @@
 				 subdomains = new SubDomain[ Gh.nbsubdomains];
 				nbsubdomains =Gh.nbsubdomains;
-				long err=0;
 				CreateSingleVertexToTriangleConnectivity();
 				long * mark = new long[nbt];
@@ -2638,5 +2627,4 @@
 					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
@@ -2773,5 +2761,5 @@
 			vertices=new BamgVertex[maxnbv];
 			_assert_(vertices);
-			orderedvertices=new (BamgVertex* [maxnbv]);
+			orderedvertices=new BamgVertex* [maxnbv];
 			_assert_(orderedvertices);
 			triangles=new Triangle[maxnbt];
@@ -3015,9 +3003,4 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::isCracked{{{*/
-	int Mesh::isCracked() const {
-		return NbCrackedVertices != 0;
-	}
-	/*}}}*/
 	/*FUNCTION Mesh::MakeGeomEdgeToEdge{{{*/
 	Edge** Mesh::MakeGeomEdgeToEdge() {
@@ -3027,5 +3010,5 @@
 			_error_("!Gh.nbe");
 		}
-		Edge **e= new (Edge* [Gh.nbe]);
+		Edge **e= new Edge* [Gh.nbe];
 
 		long i;
@@ -3108,8 +3091,5 @@
 	void Mesh::MakeBamgQuadtree() {  
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeBamgQuadtree)*/
-
-		long int verbose=0;
-		if (  !quadtree )  quadtree = new BamgQuadtree(this);
-
+		if(!quadtree) quadtree = new BamgQuadtree(this);
 	}
 	/*}}}*/
@@ -3135,5 +3115,5 @@
 			for (int j=0;j<3;j++){
 				Triangle &tt = *t.TriangleAdj(j);
-				if ( ! &tt ||  it < GetId(tt) && ( tt.link || t.link)){
+				if ( (!&tt ||  it < GetId(tt)) && ( tt.link || t.link)){
 					BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
 					BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
@@ -3313,16 +3293,10 @@
 			}
 
-		} 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 ;
-	}
-	/*}}}*/
+		}while(nbv!=nbvold);
+		delete [] first_np_or_next_t;
+
+		long NbSwapf =0;
+		for(i=0;i<nbv;i++) NbSwapf += vertices[i].Optim(0);
+	}/*}}}*/
 	/*FUNCTION Mesh::ProjectOnCurve{{{*/
 	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,
@@ -3765,5 +3739,4 @@
 		/*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;
@@ -3830,78 +3803,4 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::VerticesRenumber{{{*/
-	void Mesh::VerticesRenumber(long * renu) {
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingVertex)*/
-
-		// warning be carfull because pointer
-		// from on mesh to over mesh 
-		//  --  so do ReNumbering at the beginning
-		BamgVertex * ve = vertices+nbv;
-		long it,ie,i;
-
-		_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 BamgQuadtree(this);
-		}
-
-		for ( it=0;it<nbv;it++) renu[i]= -renu[i]-1;
-	}
-	/*}}}*/
 /*FUNCTION Mesh::SetIntCoor{{{*/
 void Mesh::SetIntCoor(const char * strfrom) {
@@ -3964,113 +3863,4 @@
 
 	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
-}
-/*}}}*/
-/*FUNCTION Mesh::ShowRegulaty{{{*/
-void  Mesh::ShowRegulaty() const {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr>*/
-
-	const  double  sqrt32=sqrt(3.)*0.5; 
-	const double  aireKh=sqrt32*0.5;
-	D2  Beq(1,0),Heq(0.5,sqrt32);
-	D2xD2 Br(D2xD2(Beq,Heq).t());
-	D2xD2 B1r(Br.inv());
-	double gammamn=1e100,hmin=1e100;
-	double gammamx=0,hmax=0;
-	double beta=1e100;
-	double beta0=0;
-	double  alpha2=0;
-	double area=0,Marea=0;
-	// double cf= double(coefIcoor);
-	// double cf2= 6.*cf*cf;
-	int nt=0;
-	for (int it=0;it<nbt;it++)
-	 if ( triangles[it].link){
-		 Triangle &K=triangles[it];
-		 double  area3= Area2((R2) K[0],(R2) K[1],(R2) K[2])/6.;
-		 area+= area3;
-		 D2xD2 B_Kt(K[0],K[1],K[2]);
-		 D2xD2 B_K(B_Kt.t());
-		 D2xD2 B1K = Br*B_K.inv();
-		 D2xD2 BK =  B_K*B1r;
-		 D2xD2 B1B1 = B1K.t()*B1K;
-		 Metric MK(B1B1.x.x,B1B1.x.y,B1B1.y.y);
-		 EigenMetric VMK(MK);
-		 alpha2 = Max(alpha2,Max(VMK.lambda1/VMK.lambda2,VMK.lambda2/VMK.lambda1));
-		 double betaK=0;
-
-		 for (int j=0;j<3;j++)
-			{
-			 double he= Norme2(R2(K[j],K[(j+1)%3]));
-			 hmin=Min(hmin,he);
-			 hmax=Max(hmax,he);
-			 BamgVertex & v=K[j];
-			 D2xD2 M((Metric)v);
-			 betaK += sqrt(M.det());
-
-			 D2xD2 BMB = BK.t()*M*BK;
-			 Metric M1(BMB.x.x,BMB.x.y,BMB.y.y);
-			 EigenMetric VM1(M1);
-			 gammamn=Min3(gammamn,VM1.lambda1,VM1.lambda2);
-			 gammamx=Max3(gammamx,VM1.lambda1,VM1.lambda2);		
-			}
-		 betaK *= area3;//  1/2 (somme sqrt(det))* area(K)
-		 Marea+= betaK;
-		 beta=min(beta,betaK);
-		 beta0=max(beta0,betaK);
-		}   
-	area*=3; 
-	gammamn=sqrt(gammamn);
-	gammamx=sqrt(gammamx);    
-	_printf_("   Adaptmesh info:\n");
-	_printf_("      number of triangles = " << nt << "\n");
-	_printf_("      hmin = " << hmin << ", hmax=" << hmax << "\n");
-	_printf_("      area = " << area << ", M area = " << Marea << ", M area/( |Khat| nt) = " <<  Marea/(aireKh*nt) << "\n");
-	_printf_("      infinite-regularity(?): min = " << gammamn << ", max = " << gammamx << "\n");
-	_printf_("      anisomax = " << pow(alpha2,0.5) << ", beta max = " << 1./pow(beta/aireKh,0.5) << ", min = " << 1./pow(beta0/aireKh,0.5) << "\n");
-}
-/*}}}*/
-/*FUNCTION Mesh::ShowHistogram{{{*/
-void  Mesh::ShowHistogram() const {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ShowHistogram)*/
-
-	const long kmax=10;
-	const double llmin = 0.5,llmax=2;
-	const double lmin=log(llmin),lmax=log(llmax),delta= kmax/(lmax-lmin);
-	long histo[kmax+1];
-	long i,it,k, nbedges =0;
-	for (i=0;i<=kmax;i++) histo[i]=0;
-	for (it=0;it<nbt;it++)
-	 if ( triangles[it].link) 
-		{
-
-		 for (int j=0;j<3;j++)
-			{
-			 Triangle *ta = triangles[it].TriangleAdj(j);
-			 if ( !ta || !ta->link || GetId(ta) >= it) 
-				{ 
-				 BamgVertex & vP = triangles[it][VerticesOfTriangularEdge[j][0]];
-				 BamgVertex & vQ = triangles[it][VerticesOfTriangularEdge[j][1]];
-				 if ( !& vP || !&vQ) continue;
-				 R2 PQ = vQ.r - vP.r;
-				 double l = log(LengthInterpole(vP,vQ,PQ));
-				 nbedges++;
-				 k = (int) ((l - lmin)*delta);
-				 k = Min(Max(k,0L),kmax);
-				 histo[k]++;
-				}
-			}
-		}  
-	_printf_(" --- Histogram of the unit mesh,  nb of edges = " << nbedges << "\n");
-	_printf_("      length of edge in   | %% of edge  | Nb of edges \n"); 
-	_printf_("      --------------------+-------------+-------------\n"); 
-	for   (i=0;i<=kmax;i++){ 
-		if (i==0) _printf_( "      " << setw(10) << 0.);
-		else      _printf_( "      " << setw(10) << exp(lmin+i/delta));
-		if (i==kmax) _printf_("          +inf   ");
-		else      _printf_( "      " << setw(10) << exp(lmin+(i+1)/delta));
-		_printf_("|  " << setw(10) << (long((10000. * histo[i])/ nbedges)/100.) << " |\n");
-		_printf_("  " << histo[i] << "\n");
-	}
-	_printf_("      --------------------+-------------+-------------\n"); 
 }
 /*}}}*/
@@ -4138,7 +3928,7 @@
 	 first_np_or_next_t1[i]=-1;
 	kk=0;
-	while (Head0>=0&& kk++<100) {
+	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) {
+		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;
@@ -4195,510 +3985,4 @@
 }
 /*}}}*/
-	/*FUNCTION Mesh::SplitElement{{{*/
-	int  Mesh::SplitElement(int choice){
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/SplitElement)*/
-
-		long int verbose=0;
-
-		Direction NoDirOfSearch;
-		const  int withBackground = &BTh != this && &BTh;
-
-		TrianglesRenumberBySubDomain();
-		//int nswap =0;
-		const long nfortria( choice ? 4 : 6);
-		if(withBackground) 
-		  {
-			BTh.SetVertexFieldOn();
-			SetVertexFieldOnBTh();
-		  }
-		else
-		 BTh.SetVertexFieldOn();
-
-		long newnbt=0,newnbv=0;
-		long * kedge = 0;
-		long newnbq=nbq;
-		long * ksplit= 0, * ksplitarray=0;
-		long kkk=0;
-		int ret =0;
-		if (maxnbv<nbv+nbe) return 1;//   
-		// 1) create  the new points by spliting the internal edges 
-		// set the 
-		long nbvold = nbv;
-		long nbtold = nbt;
-		long nbtoutold  = nbtout;
-		long  NbEdgeOnGeom=0;
-		long i;
-
-		nbt = nbt - nbtout; // remove all the  the ouside triangles 
-		long nbtsave = nbt;
-		Triangle * lastT = triangles + nbt;
-		for (i=0;i<nbe;i++)
-		 if(edges[i].GeomEdgeHook) NbEdgeOnGeom++;
-		long newnbe=nbe+nbe;
-		//  long newNbVerticesOnGeomVertex=NbVerticesOnGeomVertex;
-		long newNbVerticesOnGeomEdge=NbVerticesOnGeomEdge+NbEdgeOnGeom;
-		// long newNbVertexOnBThVertex=NbVertexOnBThVertex;
-		long newNbVertexOnBThEdge=withBackground ? NbVertexOnBThEdge+NbEdgeOnGeom:0;
-
-		// do allocation for pointeur to the geometry and background
-		VertexOnGeom * newVerticesOnGeomEdge = new VertexOnGeom[newNbVerticesOnGeomEdge];
-		VertexOnEdge *newVertexOnBThEdge = newNbVertexOnBThEdge ?  new VertexOnEdge[newNbVertexOnBThEdge]:0;
-		if (NbVerticesOnGeomEdge)
-		 memcpy(newVerticesOnGeomEdge,VerticesOnGeomEdge,sizeof(VertexOnGeom)*NbVerticesOnGeomEdge);
-		if (NbVertexOnBThEdge)
-		 memcpy(newVertexOnBThEdge,VertexOnBThEdge,sizeof(VertexOnEdge)*NbVertexOnBThEdge);
-		Edge *newedges = new Edge [newnbe];
-		//  memcpy(newedges,edges,sizeof(Edge)*nbe);
-		SetOfEdges4 * edge4= new SetOfEdges4(nbe,nbv);
-		long k=nbv;
-		long kk=0;
-		long kvb = NbVertexOnBThEdge;
-		long kvg = NbVerticesOnGeomEdge;
-		long ie =0;
-		Edge ** edgesGtoB=0;
-		if (withBackground)
-		 edgesGtoB= BTh.MakeGeomEdgeToEdge();
-		long ferr=0;
-		for (i=0;i<nbe;i++)
-		 newedges[ie].GeomEdgeHook=0;
-
-		for (i=0;i<nbe;i++)
-		  {
-			GeomEdge *ong =  edges[i].GeomEdgeHook;
-
-			newedges[ie]=edges[i];
-			newedges[ie].adj[0]=newedges+(edges[i].adj[0]-edges) ;
-			newedges[ie].adj[1]=newedges + ie +1;
-			R2 A = edges[i][0],B = edges[i][1];
-
-			kk += (i == edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
-			if (ong) // a geometrical edges 
-			  { 
-				if (withBackground){
-					// walk on back ground mesh 
-					//  newVertexOnBThEdge[ibe++] = VertexOnEdge(vertices[k],bedge,absicsseonBedge); 
-					// a faire -- difficile 
-					// the first PB is to now a background edge between the 2 vertices
-					if (!edgesGtoB){
-						_error_("!edgesGtoB");
-					}
-					ong= ProjectOnCurve(*edgesGtoB[Gh.GetId(edges[i].GeomEdgeHook)],
-								edges[i][0],edges[i][1],0.5,vertices[k],
-								newVertexOnBThEdge[kvb],
-								newVerticesOnGeomEdge[kvg++]);
-					vertices[k].ReferenceNumber= edges[i].ReferenceNumber;
-					vertices[k].DirOfSearch =   NoDirOfSearch;        
-					;
-					// get the Info on background mesh 
-					double s =        newVertexOnBThEdge[kvb];
-					BamgVertex &  bv0  = newVertexOnBThEdge[kvb][0];
-					BamgVertex &  bv1  = newVertexOnBThEdge[kvb][1];
-					// compute the metrix of the new points 
-					vertices[k].m =  Metric(1-s,bv0,s,bv1); 
-					kvb++;
-				  }
-				else 
-				  {
-					ong=Gh.ProjectOnCurve(edges[i],
-								0.5,vertices[k],newVerticesOnGeomEdge[kvg++]);
-					// vertices[k].i = R2ToI2( vertices[k].r);
-					vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
-					vertices[k].DirOfSearch = NoDirOfSearch;
-					vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);	      
-				  }  
-			  }
-			else // straigth line edge ---
-			  { 
-				vertices[k].r = ((R2) edges[i][0] + (R2)  edges[i][1] )*0.5;
-				vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);
-				vertices[k].GeomEdgeHook = 0;
-			  }
-			//vertices[k].i = R2ToI2( vertices[k].r);
-			R2 AB =  vertices[k].r;
-			R2 AA = (A+AB)*0.5;
-			R2 BB = (AB+B)*0.5;
-			vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
-			vertices[k].DirOfSearch = NoDirOfSearch;
-
-			newedges[ie].GeomEdgeHook = Gh.Containing(AA,ong);
-			newedges[ie++].v[1]=vertices+k;
-
-			newedges[ie]=edges[i];
-			newedges[ie].adj[0]=newedges + ie -1;
-			newedges[ie].adj[1]=newedges+(edges[i].adj[1]-edges) ;
-			newedges[ie].GeomEdgeHook =  Gh.Containing(BB,ong);
-			newedges[ie++].v[0]=vertices+k;
-			k++;
-		  }
-		if (edgesGtoB) delete [] edgesGtoB;
-		edgesGtoB=0;
-
-		newnbv=k;
-		newNbVerticesOnGeomEdge=kvg;
-		if (newnbv> maxnbv) goto Error;// bug 
-
-		nbv = k;
-
-		kedge = new long[3*nbt+1];
-		ksplitarray = new long[nbt+1];
-		ksplit = ksplitarray +1; // because ksplit[-1] == ksplitarray[0]
-
-		for (i=0;i<3*nbt;i++)
-		 kedge[i]=-1;
-
-		//  
-
-		for (i=0;i<nbt;i++) {
-			Triangle & t = triangles[i];
-			if (!t.link){
-				_error_("!t.link");
-			}
-			for(int j=0;j<3;j++)
-			  {
-				const AdjacentTriangle ta = t.Adj(j);
-				const Triangle & tt = ta;
-				if (&tt >= lastT)
-				 t.SetAdj2(j,0,0);// unset adj
-				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
-				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
-				long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
-				if (ke>0) 
-				  {
-					long ii = GetId(tt);
-					int  jj = ta;
-					long ks = ke + nbvold;
-					kedge[3*i+j] = ks;
-					if (ii<nbt) // good triangle
-					 kedge[3*ii+jj] = ks;
-					BamgVertex &A=vertices[ks];
-					double aa,bb,cc,dd;
-					if ((dd=Area2(v0.r,v1.r,A.r)) >=0){
-						// warning PB roundoff error 
-						if (t.link && ( (aa=Area2( A.r    , t[1].r , t[2].r )) < 0.0 
-										||   (bb=Area2( t[0].r , A.r    , t[2].r )) < 0.0  
-										||   (cc=Area2( t[0].r , t[1].r , A.r    )) < 0.0)){
-							_printf_(ke + nbvold << " not in triangle " << i << " In= " << !!t.link << " " << aa << " " << bb << " " << cc << " " << dd << "\n");
-							_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_(ke + nbvold << " not in triangle " << ii << " In= " << !!tt.link << " " << aa << " " << bb << " " << cc << " " << dd << "\n");
-							_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    = " << nbq << "\n");
-			_printf_("   number of triangles         = " << nbt-nbtout- nbq*2 << "\n");
-			_printf_("   number of outside triangles = " << nbtout << "\n");
-		}
-
-		return 0; //ok
-
-Error:
-		nbv = nbvold;
-		nbt = nbtold;
-		nbtout = nbtoutold;
-		// cleaning memory ---
-		delete [] newedges;
-		if (ksplitarray) delete [] ksplitarray;
-		if (kedge) delete [] kedge;
-		if (newVerticesOnGeomEdge) delete [] newVerticesOnGeomEdge;
-		if (edge4) delete edge4;
-		if(newVertexOnBThEdge) delete []  newVertexOnBThEdge;
-
-		return ret; // ok 
-	}
-	/*}}}*/
 /*FUNCTION Mesh::SplitInternalEdgeWithBorderVertices{{{*/
 long  Mesh::SplitInternalEdgeWithBorderVertices(){
@@ -4888,5 +4172,4 @@
 	/*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;   
@@ -4937,5 +4220,5 @@
 	//Vertices
 	if(verbose) _printf_("Reading vertices (" << nbv << ")\n");
-	for (i=0;i<nbv;i++){
+	for(i=0;i<nbv;i++){
 		vertices[i].r.x=x[i];
 		vertices[i].r.y=y[i];
@@ -5415,5 +4698,5 @@
 
 				/*Initialize variables*/
-				double Lstep=0,Lcurve=0;    // step between two points   (phase==1) 
+				double Lstep=0;             // step between two points   (phase==1) 
 				long NbCreatePointOnCurve=0;// Nb of new points on curve (phase==1) 
 
@@ -5548,5 +4831,4 @@
 						long NbSegOnCurve = Max((long)(L+0.5),(long) 1);// nb of seg
 						Lstep = L/NbSegOnCurve; 
-						Lcurve = L;
 						NbCreatePointOnCurve = NbSegOnCurve-1;
 						NbOfNewEdge += NbSegOnCurve;
@@ -5679,11 +4961,11 @@
 				_error_("!v1 || !v2");
 			}
-			Icoor2 detss = 0,l=0,ks;
-			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+			Icoor2 detss = 0,l=0;
+			while ((SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
 			 if(l++ > 10000000) {
 				 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
 			 }
 			BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
-			if (( aa == &a ) && (bb == &b) ||  (bb ==  &a ) && (aa == &b)) {
+			if (((aa == &a ) && (bb == &b)) ||((bb ==  &a ) && (aa == &b))){
 				tc.SetLock();
 				a.Optim(1,0);
@@ -5827,10 +5109,10 @@
 			detsb=-detsb;
 
-			if (ToSwap) 
+			if(ToSwap){
 			 if (dets2 < 0) {// haut
 				 dets1 = (ToSwap ? dets1 : detsa) ;
 				 detsa = dets2; 
 				 tt1 =  Previous(tt2) ;}
-			 else if (dets2 > 0){// bas 
+			 else if(dets2 > 0){// bas 
 				 dets1 = (ToSwap ? dets1 : detsb) ;
 				 detsb =  dets2;
@@ -5840,4 +5122,5 @@
 				 tt1 = Next(tt2);
 				 ret =0;}
+			}
 
 		}
Index: /issm/trunk/src/c/bamg/Mesh.h
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/Mesh.h	(revision 16560)
@@ -83,7 +83,5 @@
 			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) ;
@@ -92,10 +90,8 @@
 			long SplitInternalEdgeWithBorderVertices();
 			void MakeQuadrangles(double costheta);
-			int  SplitElement(int choice);
 			void MakeBamgQuadtree();
 			void NewPoints(Mesh &,BamgOpts* bamgopts,int KeepVertices=1);
 			long InsertNewPoints(long nbvold,long & NbTSwap) ; 
 			void TrianglesRenumberBySubDomain(bool justcompress=false);
-			void VerticesRenumber(long * renu);
 			void SmoothingVertex(int =3,double=0.3);
 			Metric MetricAt (const R2 &) const;
@@ -119,5 +115,4 @@
 			void BuildMetric1(BamgOpts* bamgopts);
 			void AddGeometryMetric(BamgOpts* bamgopts);
-			int  isCracked() const;
 			void BuildGeometryFromMesh(BamgOpts* bamgopts=NULL);
 			void ReconstructExistingMesh();
Index: /issm/trunk/src/c/bamg/Metric.h
===================================================================
--- /issm/trunk/src/c/bamg/Metric.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/Metric.h	(revision 16560)
@@ -72,5 +72,4 @@
 			void   Minh(double h);
 			void   Maxh(double h);
-			void   Isotrope();
 			double hmin()   const;
 			double hmax()   const;
@@ -78,6 +77,4 @@
 			double lmin()   const;
 			double Aniso2() const;
-			double Aniso()  const;
-			void   BoundAniso(const  double c);
 			inline void BoundAniso2(const double coef);
 
Index: /issm/trunk/src/c/bamg/SetOfE4.cpp
===================================================================
--- /issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 16560)
@@ -103,9 +103,4 @@
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::newarete{{{*/
-	long SetOfEdges4::newarete(long k){
-		return NbOfEdges == k+1;
-	}
-	/*}}}*/
 	/*FUNCTION  SetOfEdges4::SortAndAdd{{{*/
 	long SetOfEdges4::SortAndAdd (long ii,long jj) {
Index: /issm/trunk/src/c/bamg/SetOfE4.h
===================================================================
--- /issm/trunk/src/c/bamg/SetOfE4.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/SetOfE4.h	(revision 16560)
@@ -37,5 +37,4 @@
 			long i(long k);
 			long j(long k);
-			long newarete(long k);
 	};
 }
Index: /issm/trunk/src/c/bamg/SubDomain.cpp
===================================================================
--- /issm/trunk/src/c/bamg/SubDomain.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/SubDomain.cpp	(revision 16560)
@@ -15,9 +15,9 @@
 	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){
 		*this = Th.subdomains[i];
-		if ( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
+		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);{
+		if(edge-Th.edges<0 || edge-Th.edges>=Th.nbe){
 			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
 		}
Index: /issm/trunk/src/c/bamg/Triangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/Triangle.cpp	(revision 16560)
@@ -53,33 +53,4 @@
 		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
 	};/*}}}*/
-	/*FUNCTION Triangle::Anisotropy{{{*/
-	double Triangle::Anisotropy() const{
-
-		double lmin,lmax;
-
-		/*Get three vertices A,B and C*/
-		R2 A=*this->vertices[0];
-		R2 B=*this->vertices[1];
-		R2 C=*this->vertices[2];
-
-		/*Compute edges*/
-		R2 e1=B-A;
-		R2 e2=C-A;
-		R2 e3=B-C;
-
-		/*Compute edge length*/
-		double l1=Norme2(e1);
-		double l2=Norme2(e2);
-		double l3=Norme2(e3);
-
-		lmin=l1;
-		lmin=min(lmin,l2);
-		lmin=min(lmin,l3);
-		lmax=l1;
-		lmax=max(lmax,l2);
-		lmax=max(lmax,l3);
-
-		return lmax/lmin;
-	};/*}}}*/
 	/*FUNCTION Triangle::Length{{{*/
 	double Triangle::Length() const{
@@ -133,51 +104,4 @@
 
 		return;
-	}
-	/*}}}*/
-	/*FUNCTION Triangle::FindBoundaryEdge{{{*/
-	AdjacentTriangle Triangle::FindBoundaryEdge(int i) const{
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindBoundaryEdge)*/
-
-		/*Intermediary*/
-		Triangle* ttc=NULL;
-		int k,j,jc;
-
-		// call current triangle t
-		Triangle* t = (Triangle*)this;
-
-		//is the current triangle inside or outside?
-		int outside=!link  ;
-
-		// EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
-		// initialize j as the first vertex of the ith edge
-		j=EdgesVertexTriangle[i][0];
-
-		//Loop over the adjacent triangle of t
-		k=0;
-		do{
-			//keep track of outside
-			int outsidep = outside;
-			//increment k
-			k++;
-			//Get ttc, adjacent triangle of t with respect to vertex j
-			ttc =  t->adj[j];
-			//is the current triangle inside or outside?
-			outside = !ttc->link;
-			//if both previous triangle are outside, return
-			if (outside+outsidep == 1) return AdjacentTriangle(t,j);
-
-			//update t and j
-			t = ttc;
-			//NextEdge[3] = {1,2,0};
-			jc = NextEdge[t->AdjEdgeIndex[j]&3];
-			j = NextEdge[jc];
-
-			//check number of iterations
-			if (k>=2000){
-				_error_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
-			}
-		} while (this!= t);
-		//not found, return empty triangle
-		return AdjacentTriangle(NULL,0);
 	}
 	/*}}}*/
@@ -327,13 +251,4 @@
 			t->AdjEdgeIndex[aat]=a;
 		}
-	}/*}}}*/
-	/*FUNCTION Triangle::SetAllFlag{{{*/
-	void   Triangle::SetAllFlag(int a,int f){
-		AdjEdgeIndex[a] = (AdjEdgeIndex[a] &3) + (1020 & f);
-	}/*}}}*/
-	/*FUNCTION Triangle::SetDet{{{*/
-	void Triangle::SetDet() {
-		if(vertices[0] && vertices[1] && vertices[2])    det = bamg::det(*vertices[0],*vertices[1],*vertices[2]);
-		else det = -1; 
 	}/*}}}*/
 	/*FUNCTION Triangle::SetHidden{{{*/
Index: /issm/trunk/src/c/bamg/Triangle.h
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.h	(revision 16559)
+++ /issm/trunk/src/c/bamg/Triangle.h	(revision 16560)
@@ -40,5 +40,4 @@
 			//Methods
 			void              Echo();
-			double            Anisotropy() const;
 			double            Length() const;
 			int               swap(short a1,int=0);
@@ -47,8 +46,6 @@
 			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;
@@ -63,5 +60,4 @@
 			void              SetMarkUnSwap(int a);
 			void              SetUnMarkUnSwap(int a);
-			void              SetDet();
 
 			//Inline methods
Index: /issm/trunk/src/c/bamg/VertexOnGeom.cpp
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 16559)
+++ /issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 16560)
@@ -38,9 +38,10 @@
 		*this = rec;  
 		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
-		if (gv)
+		if(gv){
 		 if (curvilincoord < 0 )
 		  gv = ThNew.Gh.vertices + Th.Gh.GetId(gv);
 		 else
 		  ge = ThNew.Gh.edges + Th.Gh.GetId(ge);
+		}
 
 	}
Index: /issm/trunk/src/c/classes/Definition.h
===================================================================
--- /issm/trunk/src/c/classes/Definition.h	(revision 16560)
+++ /issm/trunk/src/c/classes/Definition.h	(revision 16560)
@@ -0,0 +1,19 @@
+/*!\file: Definition.h: abstract class used by some objects to behave like response objects 
+ * that can be called according to a string (the output definition)
+ */ 
+
+#ifndef _DEFINITION_H_
+#define  _DEFINITION_H_
+
+/*Headers:*/
+class FemModel;
+class Definition {
+
+	public:
+		virtual       ~Definition(){};
+		virtual char*  Name()=0;
+		virtual IssmDouble  Response(FemModel*)=0;
+
+};
+
+#endif //ifndef _DEFINITION_H_
Index: /issm/trunk/src/c/classes/DependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/DependentObject.cpp	(revision 16560)
@@ -11,9 +11,10 @@
 #include "./classes.h"
 #include "shared/shared.h"
+#include "../modules/modules.h"
 
 /*DependentObject constructors and destructor*/
 /*FUNCTION DependentObject::DependentObject(){{{*/
 DependentObject::DependentObject(){
-	this->name=NoneEnum;
+	this->name=NULL;
 	this->type=0;
 	this->index=-1;
@@ -21,7 +22,7 @@
 /*}}}*/
 /*FUNCTION DependentObject::DependentObject(int in_name, int in_type, int in_index){{{*/
-DependentObject::DependentObject(int in_name, int in_type,int in_index){
+DependentObject::DependentObject(char* in_name, int in_type,int in_index){
 
-	this->name=in_name;
+	this->name=xNew<char>(strlen(in_name)+1); xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
 	this->type=in_type;
 	this->index=in_index;
@@ -33,4 +34,5 @@
 /*FUNCTION DependentObject::~DependentObject() {{{*/
 DependentObject::~DependentObject(){ //destructor
+	xDelete<char>(this->name);
 }
 /*}}}*/
@@ -41,5 +43,5 @@
 
 	_printf_("DependentObject:\n");
-	_printf_("   name: " << EnumToStringx(this->name) << "\n");
+	_printf_("   name: " << this->name << "\n");
 	if(this->type==0)
 		_printf_("   type: scalar\n");
@@ -88,11 +90,9 @@
 void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){
 
-	if(this->name==MassFluxEnum){
-
-		/*to identify the mass flux that will be computed, we need the index of the profile: */
-		femmodel->parameters->SetParam(this->index,IndexEnum);
+	/*Is this some special type of response for which we need to go in the output definitions? :*/
+	if (StringToEnumx(this->name,false)==-1){
+		*poutput_value=OutputDefinitionsResponsex(femmodel,this->name);
 	}
-
-	femmodel->Responsex(poutput_value,this->name,0);
+	else femmodel->Responsex(poutput_value,this->name);
 
 }
Index: /issm/trunk/src/c/classes/DependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.h	(revision 16559)
+++ /issm/trunk/src/c/classes/DependentObject.h	(revision 16560)
@@ -17,5 +17,5 @@
 	public:
 
-		int name;
+		char* name;
 		int type;  /*0: scalar, 1: vertex*/
 		int index;  /*0: scalar, 1: vertex*/
@@ -23,5 +23,5 @@
 		/*DependentObject constructors, destructors {{{*/
 		DependentObject();
-		DependentObject(int name, int type,int index);
+		DependentObject(char* name, int type,int index);
 		~DependentObject();
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Element.h	(revision 16560)
@@ -15,5 +15,4 @@
 class DataSet;
 class Parameters;
-class Patch;
 class Elements;
 class Loads;
@@ -54,4 +53,5 @@
 		virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue)=0;
 		virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
+		virtual void   GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
 
 		virtual IssmDouble SurfaceArea(void)=0;
@@ -59,20 +59,13 @@
 		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
 		virtual void   ComputeStrainRate(Vector<IssmDouble>* eps)=0;
-		virtual void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes)=0;
-		virtual void   PatchFill(int* pcount, Patch* patch)=0;
-		virtual void   ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results)=0;
-		virtual void   DeleteResults(void)=0;
+		virtual void   ResultInterpolation(int* pinterpolation,int output_enum)=0;
+		virtual void   ResultToVector(Vector<IssmPDouble>* vector,int output_enum)=0;
 		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
-		virtual void   InputToResult(int enum_type,int step,IssmDouble time)=0;
 		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
-		virtual void   InputCreate(IssmDouble scalar,int name,int code)=0;
-		virtual void   InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code)=0;
-		virtual void   RequestedOutput(int output_enum,int step,IssmDouble time)=0;
+		virtual void   InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code)=0;
 
 		virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum)=0;
 		virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
 		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum)=0;
-		virtual void   GetVectorFromResults(Vector<IssmDouble>* vector,int id,int enum_in,int interp)=0;
-		virtual void   InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max)=0;
 		virtual IssmDouble TimeAdapt()=0;
 		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
@@ -95,6 +88,8 @@
 		virtual void   MaxAbsVz(IssmDouble* pmaxabsvz)=0;
 		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
+		virtual IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id)=0;
 		virtual void   ElementResponse(IssmDouble* presponse,int response_enum)=0;
 		virtual IssmDouble IceVolume(void)=0;
+		virtual IssmDouble IceVolumeAboveFloatation(void)=0;
 		virtual IssmDouble TotalSmb(void)=0;
 		#endif
@@ -106,19 +101,20 @@
 		#ifdef _HAVE_CONTROL_
 		virtual void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index)=0;
-		virtual IssmDouble ThicknessAbsMisfit(int weight_index)=0;
-		virtual IssmDouble SurfaceAbsVelMisfit(int weight_index)=0;
-		virtual IssmDouble SurfaceRelVelMisfit(int weight_index)=0;
-		virtual IssmDouble SurfaceLogVelMisfit(int weight_index)=0;
-		virtual IssmDouble SurfaceLogVxVyMisfit(int weight_index)=0;
-		virtual IssmDouble SurfaceAverageVelMisfit(int weight_index)=0;
-		virtual IssmDouble ThicknessAbsGradient(int weight_index)=0;
-		virtual IssmDouble ThicknessAlongGradient(int weight_index)=0;
-		virtual IssmDouble ThicknessAcrossGradient(int weight_index)=0;
-		virtual IssmDouble BalancethicknessMisfit(int weight_index)=0;
-		virtual IssmDouble RheologyBbarAbsGradient(int weight_index)=0;
-		virtual IssmDouble DragCoefficientAbsGradient(int weight_index)=0;
+		virtual IssmDouble ThicknessAbsMisfit(void)=0;
+		virtual IssmDouble SurfaceAbsVelMisfit(void)=0;
+		virtual IssmDouble SurfaceRelVelMisfit(void)=0;
+		virtual IssmDouble SurfaceLogVelMisfit(void)=0;
+		virtual IssmDouble SurfaceLogVxVyMisfit(void)=0;
+		virtual IssmDouble SurfaceAverageVelMisfit(void)=0;
+		virtual IssmDouble ThicknessAbsGradient(void)=0;
+		virtual IssmDouble ThicknessAlongGradient(void)=0;
+		virtual IssmDouble ThicknessAcrossGradient(void)=0;
+		virtual IssmDouble BalancethicknessMisfit(void)=0;
+		virtual IssmDouble RheologyBbarAbsGradient(void)=0;
+		virtual IssmDouble DragCoefficientAbsGradient(void)=0;
 		virtual void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index)=0;
 		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
 		virtual void   ControlInputScaleGradient(int enum_type, IssmDouble scale)=0;
+		virtual void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
 		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
 		virtual void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
@@ -126,8 +122,11 @@
 		#endif
 
+		virtual void UpdateConstraintsExtrudeFromBase(void)=0;
+		virtual void UpdateConstraintsExtrudeFromTop(void)=0;
+
 		#ifdef _HAVE_THERMAL_
-		virtual void UpdateThermalBasalConstraints(void)=0;
+		virtual void UpdateBasalConstraintsEnthalpy(void)=0;
 		virtual void ComputeBasalMeltingrate(void)=0;
-       	virtual void DrainWaterfraction(void)=0;
+		virtual void DrainWaterfraction(void)=0;
 		#endif
 
Index: /issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 16560)
@@ -128,2 +128,29 @@
 }
 /*}}}*/
+/*FUNCTION ElementHook::SpawnSegHook{{{*/
+void ElementHook::SpawnSegHook(ElementHook* triahook,int index1,int index2){
+
+	triahook->numanalyses=this->numanalyses;
+
+	int indices[2];
+	indices[0]=index1;
+	indices[1]=index2;
+
+	/*Spawn nodes hook*/
+	triahook->hnodes=new Hook*[this->numanalyses];
+	for(int i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,2);
+		}
+	}
+
+	/*do not spawn hmaterial. material will be taken care of by Tria*/
+	triahook->hmaterial=NULL;
+	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,2);
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/ElementHook.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 16560)
@@ -26,4 +26,5 @@
 		void SetHookNodes(int* node_ids,int numnodes,int analysis_counter);
 		void SpawnTriaHook(ElementHook* triahook,int location); //3d only
+		void SpawnSegHook(ElementHook* triahook,int ndex1,int index2); //2d only
 		void InitHookNeighbors(int* element_ids);               //3d only
 };
Index: /issm/trunk/src/c/classes/Elements/Elements.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 16560)
@@ -16,5 +16,4 @@
 #include "../ExternalResults/Results.h"
 #include "../ExternalResults/GenericExternalResult.h"
-#include "../Patch.h"
 #include "../../toolkits/toolkits.h"
 #include "../../shared/shared.h"
@@ -52,87 +51,4 @@
 }
 /*}}}*/
-/*FUNCTION Elements::DeleteResults{{{*/
-void Elements::DeleteResults(void){
-
-	for (int i=0;i<this->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
-		element->DeleteResults();
-	}
-}
-/*}}}*/
-/*FUNCTION Elements::ResultsToPatch{{{*/
-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=dynamic_cast<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;
-	}
-
-	/*Synchronize across cluster, so as to not end up with different sizes for each patch on each cpu: */
-	ISSM_MPI_Reduce (&numvertices,&max_numvertices,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&max_numvertices,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-	numvertices=max_numvertices;
-
-	ISSM_MPI_Reduce (&numnodes,&max_numnodes,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&max_numnodes,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-	numnodes=max_numnodes;
-
-	/*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=dynamic_cast<Element*>(this->GetObjectByOffset(i));
-		element->PatchFill(&count,patch);
-	}
-
-	return patch;
-}
-/*}}}*/
 /*FUNCTION Elements::SetCurrentConfiguration{{{*/
 void Elements::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
@@ -148,127 +64,4 @@
 	}
 
-}
-/*}}}*/
-/*FUNCTION Elements::ToResults{{{*/
-void Elements::ToResults(Results* results,Parameters* parameters){
-
-	int my_rank;
-	int num_procs;
-
-	Patch               *patch              = NULL;
-	int                 *resultsenums       = NULL;
-	int                 *resultssizes       = NULL;
-	int                 *resultssteps       = NULL;
-	IssmDouble          *resultstimes       = NULL;
-	IssmDouble          *vector_serial      = NULL;
-	Vector<IssmDouble> *vector = NULL;
-	bool                io_gather;
-	bool                results_as_patches;
-	int                 numberofvertices     ,numberofelements;
-	int                 numberofresults      ,vectorsize;
-	int                 rank;
-	int                 minrank;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-	num_procs=IssmComm::GetSize();
-
-	/*Recover parameters: */
-	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*/
-
-		/*Get rank of first cpu that has results*/
-		if(this->Size()) rank=my_rank;
-		else rank=num_procs;
-		ISSM_MPI_Allreduce (&rank,&minrank,1,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
-
-		/*see what the first element of this partition has in stock (this is common to all partitions)*/
-		if(my_rank==minrank){
-			if(this->Size()==0) _error_("Cannot write results because there is no element??");
-			Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(0));
-			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
-		}
-		ISSM_MPI_Bcast(&numberofresults,1,ISSM_MPI_INT,minrank,IssmComm::GetComm());
-
-		/*Get out if there is no results. Otherwise broadcast info*/
-		if(!numberofresults) return;
-		if(my_rank!=minrank){
-			resultsenums=xNew<int>(numberofresults);
-			resultssizes=xNew<int>(numberofresults);
-			resultstimes=xNew<IssmDouble>(numberofresults);
-			resultssteps=xNew<int>(numberofresults);
-		}
-		ISSM_MPI_Bcast(resultsenums,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
-		ISSM_MPI_Bcast(resultssizes,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
-		ISSM_MPI_Bcast(resultstimes,numberofresults,ISSM_MPI_DOUBLE,minrank,IssmComm::GetComm());
-		ISSM_MPI_Bcast(resultssteps,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
-
-		/*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: " << EnumToStringx(resultssizes[i]));
-			vector=new Vector<IssmDouble>(vectorsize);
-
-			for(int j=0;j<this->Size();j++){
-				Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(j));
-				element->GetVectorFromResults(vector,i,resultsenums[i],resultssizes[i]);
-			}
-			vector->Assemble();
-
-			/*Serialize and add to results*/
-			vector_serial=vector->ToMPISerial();
-			if(my_rank==0){
-				/*No need to add this vector for all cpus*/
-				#ifdef _HAVE_ADOLC_
-				IssmPDouble* vector_serial_passive=xNew<IssmPDouble>(vectorsize);
-				for(int k=0;k<vectorsize;k++)vector_serial_passive[k]=reCast<IssmPDouble>(vector_serial[k]);
-				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial_passive,vectorsize,1,resultssteps[i],resultstimes[i]));
-				xDelete<IssmPDouble>(vector_serial_passive);
-				#else
-				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial,vectorsize,1,resultssteps[i],resultstimes[i]));
-				#endif
-			}
-
-			/*clean up*/
-			delete vector;
-			xDelete<IssmDouble>(vector_serial);
-		}
-	}
-	else{
-		/*create patch object out of all results in this dataset: */
-		patch=this->ResultsToPatch();
-
-		/*Gather onto master cpu 0, if needed: */
-		if(io_gather)patch->Gather();
-
-		/*create result object and add to results dataset:*/
-		if (patch->maxvertices && patch->maxnodes){
-			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchVerticesEnum,patch->maxvertices,1,0));
-			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchNodesEnum,   patch->maxnodes,1,0));
-			#ifdef _HAVE_ADOLC_
-			IssmPDouble* values_passive=xNew<IssmPDouble>(patch->numrows*patch->numcols);
-			for(int k=0;k<(patch->numrows*patch->numcols);k++)values_passive[k]=reCast<IssmPDouble>(patch->values[k]);
-			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  values_passive,patch->numrows,patch->numcols,1,0));
-			xDelete<IssmPDouble>(values_passive);
-			#else
-			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  patch->values,patch->numrows,patch->numcols,1,0));
-			#endif
-		}
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(resultsenums);
-	xDelete<int>(resultssizes);
-	xDelete<int>(resultssteps);
-	xDelete<IssmDouble>(resultstimes);
-	delete patch;
 }
 /*}}}*/
@@ -302,5 +95,5 @@
 
 	local_nelem=this->Size();
-	ISSM_MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)&local_nelem,(void*)&numberofelements,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 
 	return numberofelements;
Index: /issm/trunk/src/c/classes/Elements/Elements.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Elements.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Elements.h	(revision 16560)
@@ -9,5 +9,4 @@
 class Loads;
 class Nodes;
-class Patch;
 class Results;
 
@@ -26,9 +25,6 @@
 		/*numerics*/
 		void   Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		void   DeleteResults(void);
 		int    MaxNumNodes(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);
Index: /issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 16560)
@@ -30,5 +30,4 @@
 	this->inputs            = NULL;
 	this->parameters        = NULL;
-	this->results           = NULL;
 }
 /*}}}*/
@@ -36,5 +35,4 @@
 Penta::~Penta(){
 	delete inputs;
-	delete results;
 	this->parameters=NULL;
 }
@@ -43,15 +41,11 @@
 Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)
 	:PentaRef(nummodels)
-	,ElementHook(nummodels,index+1,6,iomodel) //index+1: material id, iomodel->numberofelements+1: matpar id
-                                                                      { //i is the element index
-
-	int i;
+	,ElementHook(nummodels,index+1,6,iomodel){
+
 	int penta_elements_ids[2];
 
 	/*Checks in debugging mode*/
-	/*{{{*/
 	_assert_(iomodel->Data(MeshUpperelementsEnum));
 	_assert_(iomodel->Data(MeshLowerelementsEnum));
-	/*}}}*/
 
 	/*id: */
@@ -69,7 +63,6 @@
 	this->parameters=NULL;
 
-	/*intialize inputs and results: */
+	/*intialize inputs: */
 	this->inputs=new Inputs();
-	this->results=new Results();
 
 	/*initialize pointers:*/
@@ -112,10 +105,4 @@
 		penta->inputs=new Inputs();
 	}
-	if(this->results){
-		penta->results=(Results*)this->results->Copy();
-	}
-	else{
-		penta->results=new Results();
-	}
 	/*point parameters: */
 	penta->parameters=this->parameters;
@@ -161,13 +148,10 @@
 void Penta::BasalFrictionCreateInput(void){
 
-	/*Constants*/
-	const int  numdof=NUMVERTICES*NDOF1;
-
 	/*Intermediaries */
-	int    count;
-	IssmDouble basalfriction[NUMVERTICES]={0,0,0,0,0,0};
-	IssmDouble alpha2,vx,vy;
-	Friction*  friction=NULL;
-	GaussPenta* gauss=NULL;
+	int         count;
+	IssmDouble  basalfriction[NUMVERTICES];
+	IssmDouble  alpha2                       ,vx,vy;
+	Friction   *friction                   = NULL;
+	GaussPenta *gauss                      = NULL;
 
 	/* Basal friction can only be found at the base of an ice sheet: */
@@ -437,5 +421,4 @@
 
 	/*retrieve parameters: */
-	ElementMatrix* Ke=NULL;
 	int analysis_type;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -464,5 +447,5 @@
 			break;
 		#endif
-		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+		case L2ProjectionBaseAnalysisEnum:
 			return CreateBasalMassMatrix();
 			break;
@@ -501,5 +484,5 @@
 		#endif
 		default:
-			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << EnumToStringx(analysis_type) << " not supported yet");
 	}
 
@@ -572,12 +555,10 @@
 
 	/*retrieve parameters: */
-	ElementMatrix* Ke=NULL;
 	ElementVector* De=NULL;
 	int analysis_type;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
-	/*Checks in debugging {{{*/
+	/*Checks in debugging*/
 	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
-	/*}}}*/
 
 	switch(analysis_type){
@@ -692,6 +673,6 @@
 			break;
 		#endif
-		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			return CreatePVectorSlope();
+		case L2ProjectionBaseAnalysisEnum:
+			return CreatePVectorL2ProjectionBase();
 			break;
 		case MasstransportAnalysisEnum:
@@ -775,6 +756,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorSlope {{{*/
-ElementVector* Penta::CreatePVectorSlope(void){
+/*FUNCTION Penta::CreatePVectorL2ProjectionBase {{{*/
+ElementVector* Penta::CreatePVectorL2ProjectionBase(void){
 
 	if (!IsOnBed()) return NULL;
@@ -782,5 +763,5 @@
 	/*Call Tria function*/
 	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-	ElementVector* pe=tria->CreatePVectorSlope();
+	ElementVector* pe=tria->CreatePVectorL2Projection();
 	delete tria->material; delete tria;
 
@@ -855,15 +836,4 @@
 	_printf_("   inputs\n");
 	inputs->DeepEcho();
-	_printf_("   results\n");
-	results->DeepEcho();
-}
-/*}}}*/
-/*FUNCTION Penta::DeleteResults {{{*/
-void  Penta::DeleteResults(void){
-
-	/*Delete and reinitialize results*/
-	delete this->results;
-	this->results=new Results();
-
 }
 /*}}}*/
@@ -929,4 +899,6 @@
 		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
 	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
 
 	this->inputs->AddInput(NewTemperatureInput);
@@ -1417,10 +1389,9 @@
 	/*Recover input*/
 	Input* input=inputs->GetInput(enumtype);
-	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
-	int    numnodes = this->NumberofNodes();
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
 
 	/* Start looping on the number of vertices: */
 	GaussPenta* gauss=new GaussPenta();
-	for (int iv=0;iv<this->NumberofNodes();iv++){
+	for(int iv=0;iv<this->NumberofNodes();iv++){
 		gauss->GaussNode(this->element_type,iv);
 		input->GetInputValue(&pvalue[iv],gauss);
@@ -1433,4 +1404,17 @@
 
 	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype) {{{*/
+void Penta::GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype){
+
+	Input* input=this->material->inputs->GetInput(enumtype);
 	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
 
@@ -1529,5 +1513,4 @@
 		break;
 	case StressbalanceVerticalAnalysisEnum:
-		//GetSolutionFromInputsStressbalanceVert(solution);
 		GetSolutionFromInputsOneDof(solution, VzEnum);
 		break;
@@ -1535,9 +1518,7 @@
 	#ifdef _HAVE_THERMAL_
 	case ThermalAnalysisEnum:
-		//GetSolutionFromInputsThermal(solution);
 		GetSolutionFromInputsOneDof(solution, TemperatureEnum);
 		break;
 	case EnthalpyAnalysisEnum:
-		//GetSolutionFromInputsEnthalpy(solution);
 		GetSolutionFromInputsOneDof(solution, EnthalpyEnum);
 		break;
@@ -1657,27 +1638,4 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetVectorFromResults{{{*/
-void  Penta::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
-
-	/*Get result*/
-	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
-	if(elementresult->InstanceEnum()!=enum_in){
-		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
-	}  
-	if(interp==P1Enum){
-		int vertexpidlist[NUMVERTICES];
-		int connectivity[NUMVERTICES];
-		this->GetVertexSidList(&vertexpidlist[0]);
-		this->GetConnectivityList(&connectivity[0]);
-		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
-	}
-	else if(interp==P0Enum){
-		elementresult->GetElementVectorFromResults(vector,sid);
-	}
-	else{
-		_printf_("Interpolation " << EnumToStringx(interp) << " not supported\n");
-	}
-}
-/*}}}*/
 /*FUNCTION Penta::GetZcoord {{{*/
 IssmDouble Penta::GetZcoord(GaussPenta* gauss){
@@ -1699,5 +1657,5 @@
 	/*Computeportion of the element that is grounded*/ 
 
-	int         normal_orientation;
+	int         normal_orientation=0;
 	IssmDouble  s1,s2;
 	IssmDouble  levelset[NUMVERTICES];
@@ -1706,10 +1664,10 @@
 	GetInputListOnVertices(&levelset[0],levelsetenum);
 
-	if(levelset[0]*levelset[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
 		/*Portion of the segments*/
 		s1=levelset[2]/(levelset[2]-levelset[1]);
 		s2=levelset[2]/(levelset[2]-levelset[0]);
 
-		if(levelset[2]>0) normal_orientation=1;
+		if(levelset[2]>0.) normal_orientation=1;
 		/*New point 1*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[2][0]+s1*(xyz_list[1][0]-xyz_list[2][0]);
@@ -1732,10 +1690,10 @@
 		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[5][2]+s2*(xyz_list[3][2]-xyz_list[5][2]);
 	}
-	else if(levelset[1]*levelset[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
 		/*Portion of the segments*/
 		s1=levelset[0]/(levelset[0]-levelset[2]);
 		s2=levelset[0]/(levelset[0]-levelset[1]);
 
-		if(levelset[0]>0) normal_orientation=1;
+		if(levelset[0]>0.) normal_orientation=1;
 		/*New point 1*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[0][0]+s1*(xyz_list[2][0]-xyz_list[0][0]);
@@ -1758,10 +1716,10 @@
 		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[3][2]+s2*(xyz_list[4][2]-xyz_list[3][2]);
 	}
-	else if(levelset[0]*levelset[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
 		/*Portion of the segments*/
 		s1=levelset[1]/(levelset[1]-levelset[0]);
 		s2=levelset[1]/(levelset[1]-levelset[2]);
 
-		if(levelset[1]>0) normal_orientation=1;
+		if(levelset[1]>0.) normal_orientation=1;
 		/*New point 0*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[1][0]+s1*(xyz_list[0][0]-xyz_list[1][0]);
@@ -1784,5 +1742,5 @@
 		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[4][2]+s2*(xyz_list[5][2]-xyz_list[4][2]);
 	}
-	else if(levelset[0]==0 && levelset[1]==0){ //front is on point 0 and 1
+	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[0][0];
 		xyz_zero[3*0+1]=xyz_list[0][1];
@@ -1804,5 +1762,5 @@
 		xyz_zero[3*3+2]=xyz_list[3][2];
 	}
-	else if(levelset[0]==0 && levelset[2]==0){ //front is on point 0 and 1
+	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[2][0];
 		xyz_zero[3*0+1]=xyz_list[2][1];
@@ -1824,5 +1782,5 @@
 		xyz_zero[3*3+2]=xyz_list[5][2];
 	}
-	else if(levelset[1]==0 && levelset[2]==0){ //front is on point 0 and 1
+	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[1][0];
 		xyz_zero[3*0+1]=xyz_list[1][1];
@@ -1859,38 +1817,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputArtificialNoise{{{*/
-void  Penta::InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max){
-
-	Input* input=NULL;
-
-	/*Make a copy of the original input: */
-	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
-
-	/*ArtificialNoise: */
-	input->ArtificialNoise(min,max);
-}
-/*}}}*/
-/*FUNCTION Penta::InputCreate(IssmDouble scalar,int enum,int code);{{{*/
-void Penta::InputCreate(IssmDouble scalar,int name,int code){
-
-	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
-
-	if ((code==5) || (code==1)){ //boolean
-		this->inputs->AddInput(new BoolInput(name,reCast<bool,IssmDouble>(scalar)));
-	}
-	else if ((code==6) || (code==2)){ //integer
-		this->inputs->AddInput(new IntInput(name,reCast<int,IssmDouble>(scalar)));
-	}
-	else if ((code==7) || (code==3)){ //IssmDouble
-		this->inputs->AddInput(new DoubleInput(name,scalar));
-	}
-	else _error_("could not recognize nature of vector from code " << code);
-
-}
-/*}}}*/
-/*FUNCTION Penta::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
-void Penta::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+/*FUNCTION Penta::InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Penta::InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){
 
 	/*Intermediaries*/
@@ -1908,5 +1834,5 @@
 		for(i=0;i<6;i++){ 
 			_assert_(iomodel->elements);
-			penta_vertex_ids[i]=iomodel->elements[6*index+i]; //ids for vertices are in the elements array from Matlab
+			penta_vertex_ids[i]=iomodel->elements[6*this->sid+i]; //ids for vertices are in the elements array from Matlab
 		}
 
@@ -1947,11 +1873,11 @@
 
 			if (code==5){ //boolean
-				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool,IssmDouble>(vector[index])));
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool,IssmDouble>(vector[this->sid])));
 			}
 			else if (code==6){ //integer
-				this->inputs->AddInput(new IntInput(vector_enum,reCast<int,IssmDouble>(vector[index])));
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int,IssmDouble>(vector[this->sid])));
 			}
 			else if (code==7){ //IssmDouble
-				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[this->sid]));
 			}
 			else _error_("could not recognize nature of vector from code " << code);
@@ -2147,28 +2073,4 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputToResult{{{*/
-void  Penta::InputToResult(int enum_type,int step,IssmDouble time){
-
-	bool   found = false;
-	Input *input = NULL;
-
-	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
-	if (enum_type==MaterialsRheologyBbarEnum) input=this->material->inputs->GetInput(MaterialsRheologyBEnum);
-	else if (enum_type==MaterialsRheologyZbarEnum) input=this->material->inputs->GetInput(MaterialsRheologyZEnum);
-	else input=this->inputs->GetInput(enum_type);
-	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in penta->inputs"); why error out? if the requested input does not exist, we should still 
-	//try and output whatever we can instead of just failing.
-	if(!input)return;
-
-	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
-	 * object out of the input, with the additional step and time information: */
-	this->results->AddResult(input->SpawnResult(step,time));
-	#ifdef _HAVE_CONTROL_
-	if(input->ObjectEnum()==ControlInputEnum){
-		if(((ControlInput*)input)->gradient!=NULL) this->results->AddResult(((ControlInput*)input)->SpawnGradient(step,time));
-	}
-	#endif
-}
-/*}}}*/
 /*FUNCTION Penta::InputUpdateFromConstant(bool value, int name);{{{*/
 void  Penta::InputUpdateFromConstant(bool constant, int name){
@@ -2211,6 +2113,5 @@
 	IssmDouble  yts;
 	bool    control_analysis;
-	int     num_control_type;
-	int     num_cm_responses;
+	int     num_control_type,num_responses;
 
 	/*Fetch parameters: */
@@ -2218,5 +2119,5 @@
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
-	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);
 
 	/*Checks if debuging*/
@@ -2267,7 +2168,7 @@
 					}
 					break;
-				case MaterialsRheologyBbarEnum:
-				case MaterialsRheologyZbarEnum:
-					/*Material will take care of it*/ break;
+				/*Material will take care of it*/ 
+				case MaterialsRheologyBbarEnum: break;
+				case DamageDbarEnum:break;
 				default:
 					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
@@ -2277,36 +2178,7 @@
 	#endif
 
-	//Need to know the type of approximation for this element
+	/*Need to know the type of approximation for this element*/
 	if(iomodel->Data(FlowequationElementEquationEnum)){
-		if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HOApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,HOApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAHOApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAHOApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SIAApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,SIAApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==L1L2ApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,L1L2ApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==FSApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,FSApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAFSApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAFSApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HOFSApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,HOFSApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==NoneApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,NoneApproximationEnum));
-		}
-		else{
-			_error_("Approximation type " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(FlowequationElementEquationEnum)[index])) << " not supported yet");
-		}
+		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
 	}
 
@@ -2316,7 +2188,7 @@
 		/*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 PentaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum));
+		for(i=0;i<num_responses;i++){
+			for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(penta_vertex_ids[j]-1)*num_responses+i];
+			datasetinput->AddInput(new PentaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
 		}
 
@@ -2329,5 +2201,5 @@
 void  Penta::InputUpdateFromSolution(IssmDouble* solution){
 
-	int analysis_type;
+	int analysis_type,inputenum;
 
 	/*retreive parameters: */
@@ -2370,15 +2242,7 @@
 		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);
+	case L2ProjectionBaseAnalysisEnum:
+		this->parameters->FindParam(&inputenum,InputToL2ProjectEnum);
+		InputUpdateFromSolutionOneDofCollapsed(solution,inputenum);
 		break;
 	case MasstransportAnalysisEnum:
@@ -2676,10 +2540,5 @@
 			}
 			/*update input*/
-			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
-				material->inputs->AddInput(new PentaInput(name,values,P1Enum));
-			}
-			else{
-				this->inputs->AddInput(new PentaInput(name,values,P1Enum));
-			}
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			return;
 
@@ -2689,10 +2548,5 @@
 			}
 			/*update input*/
-			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
-				material->inputs->AddInput(new PentaInput(name,values,P1Enum));
-			}
-			else{
-				this->inputs->AddInput(new PentaInput(name,values,P1Enum));
-			}
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			return;
 
@@ -2744,4 +2598,5 @@
 				name==SurfaceEnum ||
 				name==BedEnum ||
+				name==BathymetryEnum ||
 				name==SurfaceSlopeXEnum ||
 				name==SurfaceSlopeYEnum ||
@@ -2782,4 +2637,6 @@
 				name==QmuTemperatureEnum ||
 				name==QmuMeltingEnum ||
+				name==QmuMaskGroundediceLevelsetEnum ||
+				name==QmuMaskIceLevelsetEnum ||
 				name==GiaWEnum || 
 				name==GiadWdtEnum ||
@@ -2854,55 +2711,4 @@
 }
 /*}}}*/
-/*FUNCTION Penta::ListResultsInfo{{{*/
-void Penta::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,IssmDouble** in_resultstimes,int** in_resultssteps,int* in_num_results){
-
-	/*Intermediaries*/
-	int     i;
-	int     numberofresults = 0;
-	int     *resultsenums   = NULL;
-	int     *resultssizes   = NULL;
-	IssmDouble  *resultstimes   = NULL;
-	int     *resultssteps   = NULL;
-
-	/*Checks*/
-	_assert_(in_num_results);
-
-	/*Count number of results*/
-	for(i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-		numberofresults++;
-	}
-
-	if(numberofresults){
-
-		/*Allocate output*/
-		resultsenums=xNew<int>(numberofresults);
-		resultssizes=xNew<int>(numberofresults);
-		resultstimes=xNew<IssmDouble>(numberofresults);
-		resultssteps=xNew<int>(numberofresults);
-
-		/*populate enums*/
-		for(i=0;i<this->results->Size();i++){
-			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-			resultsenums[i]=elementresult->InstanceEnum();
-			resultstimes[i]=elementresult->GetTime();
-			resultssteps[i]=elementresult->GetStep();
-			if(elementresult->ObjectEnum()==PentaP1ElementResultEnum){
-				resultssizes[i]=P1Enum;
-			}
-			else{
-				resultssizes[i]=P0Enum;
-			}
-		}
-	}
-
-	/*Assign output pointers:*/
-	*in_num_results=numberofresults;
-	*in_resultsenums=resultsenums;
-	*in_resultssizes=resultssizes;
-	*in_resultstimes=resultstimes;
-	*in_resultssteps=resultssteps;
-
-}/*}}}*/
 /*FUNCTION Penta::MinEdgeLength{{{*/
 IssmDouble Penta::MinEdgeLength(IssmDouble xyz_list[6][3]){
@@ -2957,55 +2763,4 @@
 	if(found)*pvalue=value;
 	return found;
-}
-/*}}}*/
-/*FUNCTION Penta::PatchFill{{{*/
-void  Penta::PatchFill(int* pcount, Patch* patch){
-
-	int i,count;
-	int vertices_ids[6];
-
-	/*recover pointer: */
-	count=*pcount;
-
-	/*will be needed later: */
-	for(i=0;i<6;i++) vertices_ids[i]=vertices[i]->Id(); //vertices id start at column 3 of the patch.
-
-	for(i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-
-		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
-		 *it to the result object, to fill the rest: */
-		patch->fillelementinfo(count,this->sid+1,vertices_ids,6);
-		elementresult->PatchFill(count,patch);
-
-		/*increment counter: */
-		count++;
-	}
-
-	/*Assign output pointers:*/
-	*pcount=count;
-}/*}}}*/
-/*FUNCTION Penta::PatchSize{{{*/
-void  Penta::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
-
-	int     i;
-	int     numrows       = 0;
-	int     numnodes      = 0;
-	int     temp_numnodes = 0;
-
-	/*Go through all the results objects, and update the counters: */
-	for (i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-		/*first, we have one more result: */
-		numrows++;
-		/*now, how many vertices and how many nodal values for this result? :*/
-		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
-		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
-	}
-
-	/*Assign output pointers:*/
-	*pnumrows=numrows;
-	*pnumvertices=NUMVERTICES;
-	*pnumnodes=numnodes;
 }
 /*}}}*/
@@ -3062,128 +2817,78 @@
 }
 /*}}}*/
-/*FUNCTION Penta::ReduceMatrixFS {{{*/
-void Penta::ReduceMatrixFS(IssmDouble* Ke_reduced, IssmDouble* Ke_temp){
-
-	int    i,j;
-	IssmDouble Kii[24][24];
-	IssmDouble Kib[24][3];
-	IssmDouble Kbb[3][3];
-	IssmDouble Kbi[3][24];
-	IssmDouble Kbbinv[3][3];
-	IssmDouble Kright[24][24];
-
-	/*Create the four matrices used for reduction */
-	for(i=0;i<24;i++){
-		for(j=0;j<24;j++){
-			Kii[i][j]=*(Ke_temp+27*i+j);
-		}
-		for(j=0;j<3;j++){
-			Kib[i][j]=*(Ke_temp+27*i+j+24);
-		}
-	}
-	for(i=0;i<3;i++){
-		for(j=0;j<24;j++){
-			Kbi[i][j]=*(Ke_temp+27*(i+24)+j);
-		}
-		for(j=0;j<3;j++){
-			Kbb[i][j]=*(Ke_temp+27*(i+24)+j+24);
-		}
-	}
-
-	/*Inverse the matrix corresponding to bubble part Kbb */
-	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
-
-	/*Multiply matrices to create the reduce matrix Ke_reduced */
-	TripleMultiply(&Kib[0][0],24,3,0,
-				&Kbbinv[0][0],3,3,0,
-				&Kbi[0][0],3,24,0,
-				&Kright[0][0],0);
-
-	/*Affect value to the reduced matrix */
-	for(i=0;i<24;i++) for(j=0;j<24;j++) *(Ke_reduced+24*i+j)=Kii[i][j]-Kright[i][j];
-}
-/*}}}*/
-/*FUNCTION Penta::ReduceVectorFS {{{*/
-void Penta::ReduceVectorFS(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp){
-
-	int    i,j;
-	IssmDouble Pi[24];
-	IssmDouble Pb[3];
-	IssmDouble Kbb[3][3];
-	IssmDouble Kib[24][3];
-	IssmDouble Kbbinv[3][3];
-	IssmDouble Pright[24];
-
-	/*Create the four matrices used for reduction */
-	for(i=0;i<24;i++) Pi[i]=*(Pe_temp+i);
-	for(i=0;i<3;i++) Pb[i]=*(Pe_temp+i+24);
-	for(j=0;j<3;j++){
-		for(i=0;i<24;i++){
-			Kib[i][j]=*(Ke_temp+3*i+j);
-		}
-		for(i=0;i<3;i++){
-			Kbb[i][j]=*(Ke_temp+3*(i+24)+j);
-		}
-	}
-
-	/*Inverse the matrix corresponding to bubble part Kbb */
-	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
-
-	/*Multiply matrices to create the reduce matrix Ke_reduced */
-	TripleMultiply(&Kib[0][0],24,3,0,
-				&Kbbinv[0][0],3,3,0,
-				&Pb[0],3,1,0,&Pright[0],0);
-
-	/*Affect value to the reduced matrix */
-	for(i=0;i<24;i++) *(Pe_reduced+i)=Pi[i]-Pright[i];
-}
-/*}}}*/
-/*FUNCTION Penta::RequestedOutput{{{*/
-void Penta::RequestedOutput(int output_enum,int step,IssmDouble time){
-	if(IsInput(output_enum)){
-		/*just transfer this input to results, and we are done: */
-		InputToResult(output_enum,step,time);
-	}
-	else{
-		/*this input does not exist, compute it, and then transfer to results: */
+/*FUNCTION Penta::ResultInterpolation{{{*/
+void Penta::ResultInterpolation(int* pinterpolation,int output_enum){
+
+	Input* input=this->inputs->GetInput(output_enum);
+
+	/*If this input is not already in Inputs, maybe it needs to be computed?*/
+	if(!input){
 		switch(output_enum){
-			case BasalFrictionEnum:
-
-				/*create input: */
-				BasalFrictionCreateInput();
-
-				/*transfer to results :*/
-				InputToResult(output_enum,step,time);
-
-				/*erase input: */
-				inputs->DeleteInput(output_enum);
+			case ViscousHeatingEnum:
+				this->ViscousHeatingCreateInput();
+				input=this->inputs->GetInput(output_enum);
 				break;
-			case ViscousHeatingEnum:
-
-				/*create input: */
-				ViscousHeatingCreateInput();
-
-				/*transfer to results :*/
-				InputToResult(output_enum,step,time);
-
-				/*erase input: */
-				inputs->DeleteInput(output_enum);
+			case StressTensorxxEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
 				break;
-
-			case StressTensorEnum: 
+			case StressTensorxyEnum: 
 				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);
+				input=this->inputs->GetInput(output_enum);
 				break;
-
+			case StressTensorxzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensoryyEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensoryzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensorzzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
 			default:
-				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
-				break;
-		}
-	}
+				_error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+		}
+	}
+
+	/*Assign output pointer*/
+	*pinterpolation = input->GetResultInterpolation();
+
+}
+/*}}}*/
+/*FUNCTION Penta::ResultToVector{{{*/
+void Penta::ResultToVector(Vector<IssmPDouble>* vector,int output_enum){
+
+	Input* input=this->inputs->GetInput(output_enum);
+	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+
+	switch(input->GetResultInterpolation()){
+		case P0Enum:
+			_error_("not implemented...");
+			break;
+		case P1Enum:{
+			IssmDouble  values[NUMVERTICES];
+			IssmPDouble pvalues[NUMVERTICES]; 
+			int         connectivity[NUMVERTICES];
+			int         sidlist[NUMVERTICES];
+
+			this->GetVertexSidList(&sidlist[0]);
+			this->GetConnectivityList(&connectivity[0]);
+			this->GetInputListOnVertices(&values[0],output_enum);
+			for(int i=0;i<NUMVERTICES;i++) pvalues[i] = reCast<IssmPDouble>(values[i])/reCast<IssmPDouble>(connectivity[i]);
+
+			vector->SetValues(NUMVERTICES,&sidlist[0],&pvalues[0],ADD_VAL);
+			break;
+					}
+		default:
+			_error_("interpolation "<<EnumToStringx(input->GetResultInterpolation())<<" not supported yet");
+	}
+
 
 }
@@ -3340,5 +3045,4 @@
 
 	/*Spawn material*/
-	tria->material=NULL;
 	tria->material=(Material*)this->material->copy();
 	delete tria->material->inputs;
@@ -3515,5 +3219,4 @@
 	bool       dakota_analysis;
 	bool       isFS;
-	IssmDouble beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
 	int        numnodes;
 	int*       penta_node_ids = NULL;
@@ -3523,14 +3226,7 @@
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
 	iomodel->Constant(&isFS,FlowequationIsFSEnum);
-	iomodel->Constant(&beta,MaterialsBetaEnum);
-	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
-	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
-	iomodel->Constant(&meltingpoint,MaterialsMeltingpointEnum);
-	iomodel->Constant(&latentheat,MaterialsLatentheatEnum);
 
 	/*Checks if debuging*/
-	/*{{{*/
 	_assert_(iomodel->elements);
-	/*}}}*/
 
 	/*Recover element type*/
@@ -3688,31 +3384,4 @@
 		case StressbalanceAnalysisEnum:
 
-			/*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 PentaInput(VxEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVxEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(VyEnum)){
-				for(i=0;i<6;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new PentaInput(VyEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVyEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(VzEnum)){
-				for(i=0;i<6;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new PentaInput(VzEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVzEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(PressureEnum)){
-				for(i=0;i<6;i++)nodeinputs[i]=0;
-				if(dakota_analysis){
-					this->inputs->AddInput(new PentaInput(PressureEnum,nodeinputs,P1Enum));
-					this->inputs->AddInput(new PentaInput(QmuPressureEnum,nodeinputs,P1Enum));
-				}
-				if(isFS){
-					this->inputs->AddInput(new PentaInput(PressureEnum,nodeinputs,P1Enum));
-					this->inputs->AddInput(new PentaInput(PressurePicardEnum,nodeinputs,P1Enum));
-				}
-			}
 			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==HOFSApproximationEnum){
 				/*Create VzHO and VzFS Enums*/
@@ -3744,38 +3413,4 @@
 			}
 			break;
-
-		case ThermalAnalysisEnum:
-			/*Initialize mesh velocity*/
-			for(i=0;i<6;i++)nodeinputs[i]=0;
-			this->inputs->AddInput(new PentaInput(VxMeshEnum,nodeinputs,P1Enum));
-			this->inputs->AddInput(new PentaInput(VyMeshEnum,nodeinputs,P1Enum));
-			this->inputs->AddInput(new PentaInput(VzMeshEnum,nodeinputs,P1Enum));
-			if(dakota_analysis){
-				this->inputs->AddInput(new PentaInput(QmuVxMeshEnum,nodeinputs,P1Enum));
-				this->inputs->AddInput(new PentaInput(QmuVyMeshEnum,nodeinputs,P1Enum));
-				this->inputs->AddInput(new PentaInput(QmuVzMeshEnum,nodeinputs,P1Enum));
-			}
-			break;
-
-		case EnthalpyAnalysisEnum:
-			/*Initialize mesh velocity*/
-			for(i=0;i<6;i++)nodeinputs[i]=0;
-			this->inputs->AddInput(new PentaInput(VxMeshEnum,nodeinputs,P1Enum));
-			this->inputs->AddInput(new PentaInput(VyMeshEnum,nodeinputs,P1Enum));
-			this->inputs->AddInput(new PentaInput(VzMeshEnum,nodeinputs,P1Enum));
-			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 PentaInput(EnthalpyEnum,nodeinputs,P1Enum));
-			}
-			else _error_("temperature and waterfraction required for the enthalpy solution");
-			break;
-
 		default:
 			/*No update for other solution types*/
@@ -3786,7 +3421,4 @@
 /*FUNCTION Penta::ViscousHeatingCreateInput {{{*/
 void Penta::ViscousHeatingCreateInput(void){
-
-	/*Constants*/
-	const int  numdof=NUMVERTICES*NDOF1;
 
 	/*Intermediaries*/
@@ -3795,10 +3427,6 @@
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble epsilon[6];
-	IssmDouble viscousheating[NUMVERTICES]={0,0,0,0,0,0};
+	IssmDouble viscousheating[NUMVERTICES];
 	IssmDouble thickness;
-	GaussPenta *gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
 
 	/*Retrieve all inputs and parameters*/
@@ -3810,5 +3438,5 @@
 
 	/*loop over vertices: */
-	gauss=new GaussPenta();
+	GaussPenta* gauss=new GaussPenta();
 	for (int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
@@ -3860,4 +3488,35 @@
 }
 /*}}}*/
+/*FUNCTION Penta::IceVolumeAboveFloatation {{{*/
+IssmDouble Penta::IceVolumeAboveFloatation(void){
+
+	/*Volume above floatation: H + rho_water/rho_ice*bathymetry for nodes on the bed*/
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,bed,surface,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(NoIceInElement() || IsFloating() || !IsOnBed())return 0;
+
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height above floatation*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* bed_input        = inputs->GetInput(BedEnum);        _assert_(bed_input);
+	Input* bathymetry_input = inputs->GetInput(BathymetryEnum); _assert_(bathymetry_input);
+	surface_input->GetInputAverage(&surface);
+	bed_input->GetInputAverage(&bed);
+	bathymetry_input->GetInputAverage(&bathymetry);
+
+	/*Return: */
+	return base*(surface - bed + min( rho_water/rho_ice * bathymetry, 0.) );
+}
+/*}}}*/
 /*FUNCTION Penta::MinVel{{{*/
 void  Penta::MinVel(IssmDouble* pminvel){
@@ -3924,4 +3583,28 @@
 }
 /*}}}*/
+/*FUNCTION Penta::MassFlux {{{*/
+IssmDouble Penta::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBed()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	mass_flux=tria->MassFlux(x1,y1,x2,y2,segment_id);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
 /*FUNCTION Penta::MaxAbsVx{{{*/
 void  Penta::MaxAbsVx(IssmDouble* pmaxabsvx){
@@ -4002,6 +3685,6 @@
 			*presponse=this->material->GetBbar();
 			break;
-		case MaterialsRheologyZbarEnum:
-			*presponse=this->material->GetZbar();
+		case DamageDbarEnum:
+			*presponse=this->material->GetDbar();
 			break;
 		case VelEnum:
@@ -4088,5 +3771,5 @@
 	/*Intermediaries */
 	int        stabilization;
-	int        i,j,found=0;
+	int        i,j;
 	IssmDouble Jdet,u,v,w,um,vm,wm;
 	IssmDouble h,hx,hy,hz,vx,vy,vz,vel;
@@ -4107,5 +3790,4 @@
 	IssmDouble D[3][3];
 	IssmDouble K[3][3]={0.0};
-	Tria*      tria=NULL;
 	GaussPenta *gauss=NULL;
 
@@ -4142,11 +3824,10 @@
 
 		/*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;
+		kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure); _assert_(kappa>0.);
+		D_scalar_conduct=gauss->weight*Jdet*kappa/rho_ice;
 		if(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
 
@@ -4191,5 +3872,5 @@
 		}
 
-		/*Artifficial diffusivity*/
+		/*Artificial diffusivity*/
 		if(stabilization==1){
 			/*Build K: */
@@ -4197,7 +3878,9 @@
 			vel=sqrt(vx*vx + vy*vy + vz*vz)+1.e-14;
 			h=sqrt( pow(hx*vx/vel,2) + pow(hy*vy/vel,2) + pow(hz*vz/vel,2));
+
 			K[0][0]=h/(2*vel)*vx*vx;  K[0][1]=h/(2*vel)*vx*vy; K[0][2]=h/(2*vel)*vx*vz;
 			K[1][0]=h/(2*vel)*vy*vx;  K[1][1]=h/(2*vel)*vy*vy; K[1][2]=h/(2*vel)*vy*vz;
 			K[2][0]=h/(2*vel)*vz*vx;  K[2][1]=h/(2*vel)*vz*vy; K[2][2]=h/(2*vel)*vz*vz;
+
 			D_scalar_stab=gauss->weight*Jdet;
 			if(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
@@ -4324,5 +4007,5 @@
 	/*Intermediaries */
 	int        stabilization;
-	int        i,j,found=0;
+	int        i,j;
 	IssmDouble Jdet,u,v,w,um,vm,wm,vel;
 	IssmDouble h,hx,hy,hz,vx,vy,vz;
@@ -4340,5 +4023,4 @@
 	IssmDouble D[3][3];
 	IssmDouble K[3][3]={0.0};
-	Tria*      tria=NULL;
 	GaussPenta *gauss=NULL;
 
@@ -4389,5 +4071,4 @@
 
 		/*Advection: */
-
 		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
 		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
@@ -4544,6 +4225,6 @@
 
 	/*Intermediaries*/
-	int    i,j,found=0;
-	int    friction_type,stabilization;
+	int        i;
+	int        stabilization;
 	IssmDouble Jdet,phi,dt;
 	IssmDouble rho_ice,heatcapacity;
@@ -4554,5 +4235,4 @@
 	IssmDouble u,v,w;
 	IssmDouble scalar_def,scalar_transient;
-	IssmDouble temperature_list[NUMVERTICES];
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble L[numdof];
@@ -4600,5 +4280,6 @@
 		scalar_def=phi/rho_ice*Jdet*gauss->weight;
 		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
-
+		
+		/*TODO: add -beta*laplace T_m(p)*/
 		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
 
@@ -4619,5 +4300,6 @@
 			enthalpypicard_input->GetInputValue(&enthalpypicard, gauss);
 			kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
-			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa);
+			kappa/=rho_ice;
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa); 
 
 			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
@@ -4702,6 +4384,7 @@
 	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
 	IssmDouble Jdet2d,dt;
-	IssmDouble rho_ice,heatcapacity,geothermalflux_value;
-	IssmDouble basalfriction,alpha2,vx,vy;
+	IssmDouble rho_ice,heatcapacity;
+	IssmDouble geothermalflux_value, heatflux_value;
+	IssmDouble basalfriction,alpha2,vx,vy,vz;
 	IssmDouble scalar,enthalpy,enthalpyup;
 	IssmDouble pressure,pressureup;
@@ -4739,4 +4422,5 @@
 	gauss=new GaussPenta(0,1,2,2);
 	gaussup=new GaussPenta(3,4,5,2);
+
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -4749,30 +4433,35 @@
 		enthalpy_input->GetInputValue(&enthalpy,gauss);
 		pressure_input->GetInputValue(&pressure,gauss);
-		if(enthalpy>=matpar->PureIceEnthalpy(pressure)){
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+
+		if((watercolumn<=0.) && (enthalpy<matpar->PureIceEnthalpy(pressure))){
+			/* the above check is equivalent to 
+			 NOT ((watercolumn>0.) AND (enthalpy<PIE)) AND (enthalpy<PIE)*/
+			geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
+
+			friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+			vx_input->GetInputValue(&vx,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			vz_input->GetInputValue(&vz,gauss);
+			basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0)+pow(vz,2.0));
+
+			heatflux_value=(basalfriction+geothermalflux_value)/(rho_ice);
+			scalar=gauss->weight*Jdet2d*heatflux_value;
+			if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
+			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+		}
+		else if(enthalpy>=matpar->PureIceEnthalpy(pressure)){
+			/* check positive thickness of temperate basal ice layer */
 			enthalpy_input->GetInputValue(&enthalpyup,gaussup);
 			pressure_input->GetInputValue(&pressureup,gaussup);
 			if(enthalpyup>=matpar->PureIceEnthalpy(pressureup)){
-				// temperate ice has positive thickness: grad enthalpy*n=0.
+				// TODO: temperate ice has positive thickness: grad enthalpy*n=0.
 			}
 			else{
-				// only base temperate, set Dirichlet BCs in Penta::UpdateThermalBasalConstraints()
+				// only base temperate, set Dirichlet BCs in Penta::UpdateBasalConstraintsEnthalpy()
 			}
 		}
-		else{
-			watercolumn_input->GetInputValue(&watercolumn,gauss);
-			if(watercolumn==0.){
-				/*add geothermal heat flux and basal friction*/
-				geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
-				friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
-				vx_input->GetInputValue(&vx,gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0));
-
-				scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(rho_ice);
-				if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
-
-				for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
-			}
-			else{  /*do nothing (water layer acts as insulation)*/  }
+		else {
+			// base cold, but watercolumn positive. Set base to h_pmp.
 		}
 	}
@@ -4813,6 +4502,6 @@
 
 	/*Intermediaries*/
-	int    i,j,found=0;
-	int    friction_type,stabilization;
+	int        i;
+	int        stabilization;
 	IssmDouble Jdet,phi,dt;
 	IssmDouble rho_ice,heatcapacity;
@@ -4822,5 +4511,4 @@
 	IssmDouble u,v,w;
 	IssmDouble scalar_def,scalar_transient;
-	IssmDouble temperature_list[NUMVERTICES];
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble L[numdof];
@@ -4844,6 +4532,6 @@
 	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
 	Input* temperature_input=NULL;
-	if (reCast<bool,IssmDouble>(dt)) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
-	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+	if(reCast<bool,IssmDouble>(dt)) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
+	if(stabilization==2) diameter=MinEdgeLength(xyz_list);
 
 	/* Start  looping on the number of gaussian points: */
@@ -4957,14 +4645,14 @@
 
 	/*Intermediaries */
-	int        i,j;
-	int        analysis_type;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble Jdet2d,dt;
-	IssmDouble rho_ice,heatcapacity,geothermalflux_value;
-	IssmDouble basalfriction,alpha2,vx,vy;
-	IssmDouble basis[NUMVERTICES];
-	IssmDouble scalar;
-	Friction*  friction=NULL;
+	int         i,j;
+	int         analysis_type;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble  Jdet2d,dt;
+	IssmDouble  rho_ice,heatcapacity,geothermalflux_value;
+	IssmDouble  basalfriction,alpha2,vx,vy;
+	IssmDouble  basis[NUMVERTICES];
+	IssmDouble  scalar;
+	Friction*   friction=NULL;
 	GaussPenta* gauss=NULL;
 
@@ -5017,65 +4705,4 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsThermal{{{*/
-void  Penta::GetSolutionFromInputsThermal(Vector<IssmDouble>* solution){
-
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int         i;
-	int        *doflist = NULL;
-	IssmDouble  values[numdof];
-	IssmDouble  temp;
-	GaussPenta *gauss = NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	Input* t_input=inputs->GetInput(TemperatureEnum); _assert_(t_input);
-
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
-		/*Recover temperature*/
-		gauss->GaussVertex(i);
-		t_input->GetInputValue(&temp,gauss);
-		values[i]=temp;
-	}
-
-	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<int>(doflist);
-}
-/*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsEnthalpy{{{*/
-void  Penta::GetSolutionFromInputsEnthalpy(Vector<IssmDouble>* solution){
-
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int*        doflist=NULL;
-	IssmDouble  values[numdof];
-	IssmDouble  enthalpy;
-	GaussPenta *gauss=NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	Input* h_input=inputs->GetInput(EnthalpyEnum); _assert_(h_input);
-
-	gauss=new GaussPenta();
-	for(int i=0;i<NUMVERTICES;i++){
-		/*Recover temperature*/
-		gauss->GaussVertex(i);
-		h_input->GetInputValue(&enthalpy,gauss);
-		values[i]=enthalpy;
-	}
-
-	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<int>(doflist);
-}
-/*}}}*/
 /*FUNCTION Penta::InputUpdateFromSolutionThermal {{{*/
 void  Penta::InputUpdateFromSolutionThermal(IssmDouble* solution){
@@ -5090,5 +4717,5 @@
 	IssmDouble  B_average,s_average;
 	int        *doflist = NULL;
-	IssmDouble  pressure[numdof];
+	bool        hack    = false;
 
 	/*Get dof list: */
@@ -5098,7 +4725,4 @@
 	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*/
@@ -5107,4 +4731,15 @@
 		//if(values[i]>275)    _printf_("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)\n");
 	}
+
+	if(hack){
+		/*Force temperature between [Tpmp-50 Tpmp] to disable penalties*/
+		IssmDouble pressure[numdof];
+		GetInputListOnVertices(&pressure[0],PressureEnum);
+		for(i=0;i<numdof;i++){
+			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.;
+		}
+	}
+
 
 	/*Get all inputs and parameters*/
@@ -5216,6 +4851,7 @@
 			case LliboutryDuvalEnum:
 				B_average=LliboutryDuval((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0,
-							(pressure[0]+pressure[1]+pressure[2]+pressure[3]+pressure[4]+pressure[5])/6.0,
-							material->GetN());
+																 (pressure[0]+pressure[1]+pressure[2]+pressure[3]+pressure[4]+pressure[5])/6.0,
+																 material->GetN(), 
+																 matpar->GetBeta(), matpar->GetReferenceTemperature(), matpar->GetHeatCapacity(), matpar->GetLatentHeat());
 				for(i=0;i<numdof;i++) B[i]=B_average;
 				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
@@ -5233,12 +4869,13 @@
 }
 /*}}}*/
-/*FUNCTION Penta::UpdateThermalBasalConstraints{{{*/
-void  Penta::UpdateThermalBasalConstraints(void){
+/*FUNCTION Penta::UpdateBasalConstraintsEnthalpy{{{*/
+void  Penta::UpdateBasalConstraintsEnthalpy(void){
 
 	/*Intermediary*/
-	bool        isenthalpy,isdynamicbasalspc,istemperatelayer;
+	bool        isenthalpy,isdynamicbasalspc,setspc;
 	int         numindices, numindicesup;
-	IssmDouble  h_pmp,pressure, pressureup;
-    IssmDouble  enthalpy, enthalpyup;
+	IssmDouble  pressure, pressureup;
+	IssmDouble  h_pmp, enthalpy, enthalpyup;
+	IssmDouble  watercolumn;
 	int        *indices = NULL, *indicesup = NULL;
 
@@ -5249,56 +4886,56 @@
 	parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
 	if(!isenthalpy) return;
-	//parameters->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
-	isdynamicbasalspc = true;
+	parameters->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
 	if(!isdynamicbasalspc) return;
 
 	/*Fetch indices of basal & surface nodes for this finite element*/
 	BasalNodeIndices(&numindices,&indices,this->element_type);
-    SurfaceNodeIndices(&numindicesup,&indicesup,this->element_type);
-    _assert_(numindices==numindicesup);
+	SurfaceNodeIndices(&numindicesup,&indicesup,this->element_type);
+	_assert_(numindices==numindicesup);
 
 	/*Get parameters and inputs: */
 	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
-    Input* enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
-
-	/*if there is a temperate layer of positive thickness, set enthalpy=h_pmp at that node*/
+	Input* enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum); //_assert_(watercolumn_input);
+
+	/*if there is a temperate layer of zero thickness, set spc enthalpy=h_pmp at that node*/
 	GaussPenta* gauss=new GaussPenta();
-    GaussPenta* gaussup=new GaussPenta();
+	GaussPenta* gaussup=new GaussPenta();
 	for(int i=0;i<numindices;i++){
 		gauss->GaussNode(this->element_type,indices[i]);
-        gaussup->GaussNode(this->element_type,indicesup[i]); // TODO: check: are the nodes corresponding?
-
-		/*Check wether there is a temperate layer at the base or not -> TODO: Johannes:) */
-        /*check if node is temperate, if not, return*/
-        enthalpy_input->GetInputValue(&enthalpy, gauss);
+		gaussup->GaussNode(this->element_type,indicesup[i]); 
+
+		/*Check wether there is a temperate layer at the base or not */
+		/*check if node is temperate, if not, continue*/
+		enthalpy_input->GetInputValue(&enthalpy, gauss);
 		pressure_input->GetInputValue(&pressure, gauss);
-        if (enthalpy<matpar->PureIceEnthalpy(pressure)){
-          // TODO: reset, if necessary, all spcs to non-valid 
-          continue;
-        }
-        /*check if upper node is temperate. if yes, then we have a temperate layer of positive thickness. if not, continue.*/
-        enthalpy_input->GetInputValue(&enthalpyup, gaussup);
-		pressure_input->GetInputValue(&pressureup, gaussup);    
-        istemperatelayer = false;
-        if (enthalpyup>=matpar->PureIceEnthalpy(pressureup))
-          istemperatelayer=true;
-
-		/*Add Dirichlet constraint to this node if there is no layer of temperate ice with positive thickness*/
-		if(!istemperatelayer){
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		setspc = false;
+		if (enthalpy>=matpar->PureIceEnthalpy(pressure)){		
+			/*check if upper node is temperate, too. 
+				if yes, then we have a temperate layer of positive thickness and reset the spc. 
+				if not, apply dirichlet BC.*/
+			enthalpy_input->GetInputValue(&enthalpyup, gaussup);
+			pressure_input->GetInputValue(&pressureup, gaussup);    
+			setspc=((enthalpyup<matpar->PureIceEnthalpy(pressureup)) && (watercolumn>=0.))?true:false;
+		}
+
+		if (setspc) {
 			/*Calculate enthalpy at pressure melting point */
 			h_pmp=matpar->PureIceEnthalpy(pressure);
-
 			/*Apply Dirichlet condition (dof = 0 here, since there is only one degree of freedom per node)*/
 			nodes[indices[i]]->ApplyConstraint(1,h_pmp);
 		}
-        else {
-          /*remove spc*/
-          nodes[indices[i]]->DofInFSet(0);
-        }
+		else {
+			/*remove spc*/
+			nodes[indices[i]]->DofInFSet(0);
+		}
 	}
 
 	/*Free ressources:*/
 	xDelete<int>(indices);
-    xDelete<int>(indicesup);
+	xDelete<int>(indicesup);
+	delete gauss;
+	delete gaussup;
 }
 /*}}}*/
@@ -5306,4 +4943,5 @@
 void Penta::ComputeBasalMeltingrate(void){
 	/*Calculate the basal melt rates of the enthalpy model after Aschwanden 2012*/
+	/* melting rate is positive when melting, negative when refreezing*/
 
 	/* Intermediaries */
@@ -5322,5 +4960,7 @@
 	IssmDouble  vx[NUMVERTICES],vy[NUMVERTICES],vz[NUMVERTICES];
 	IssmDouble  geothermalflux[NUMVERTICES];
-	IssmDouble  dt,meltingrate_enthalpy;
+	IssmDouble  dt, yts;
+	IssmDouble  melting_overshoot,meltingrate_enthalpy;
+	IssmDouble  lambda,heating;
 	Friction   *friction  = NULL;
 
@@ -5334,5 +4974,5 @@
 	/*Fetch parameters and inputs */
 	latentheat=matpar->GetLatentHeat();
-	rho_ice=this->matpar->GetRhoIce();
+	rho_ice=matpar->GetRhoIce();
 	GetInputListOnVertices(&vx[0],VxEnum);
 	GetInputListOnVertices(&vy[0],VyEnum);
@@ -5359,17 +4999,18 @@
 		checkpositivethickness=true;
 
+		_assert_(watercolumn[iv]>=0.);
+
 		/*Calculate basal meltingrate after Fig.5 of A.Aschwanden 2012*/
 		meltingrate_enthalpy=0.;
+		heating=0.;
 		if((watercolumn[iv]>0.) && (enthalpy[iv]<matpar->PureIceEnthalpy(pressure[iv]))){
 			/*ensure that no ice is at T<Tm(p), if water layer present*/
 			enthalpy[iv]=matpar->PureIceEnthalpy(pressure[iv]); 
-			//meltingrate_enthalpy=0.;
 		}
 		else if(enthalpy[iv]<matpar->PureIceEnthalpy(pressure[iv])){
 			/*cold base: set q*n=q_geo*n+frictionheating as Neumann BC in Penta::CreatePVectorEnthalpySheet*/
-			meltingrate_enthalpy=0.;
-			checkpositivethickness=false;
-		}
-		else {/*do nothing, go to next check*/}
+			checkpositivethickness=false; // cold base, skip next test
+		}
+		else {/*we have a temperate base, go to next test*/}
 
 		if(checkpositivethickness){
@@ -5377,8 +5018,8 @@
 			istemperatelayer=false;
 			if(enthalpy[iv+3]>=matpar->PureIceEnthalpy(pressure[iv+3])) istemperatelayer=true;
-			if(istemperatelayer) for(i=0;i<3;i++) vec_heatflux[i]=0.;
+			if(istemperatelayer) for(i=0;i<3;i++) vec_heatflux[i]=0.; // TODO: add -k*nabla T_pmp
 			else{
 				enthalpy_input->GetInputDerivativeValue(&d1enthalpy[0],&xyz_list[0][0],gauss);
-				kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy[iv],pressure[iv]);
+				kappa=matpar->GetEnthalpyDiffusionParameterVolume(enthalpy[iv],enthalpy[iv+NUMVERTICES2D], pressure[iv],pressure[iv+NUMVERTICES2D]); _assert_(kappa>0.);
 				for(i=0;i<3;i++) vec_heatflux[i]=-kappa*d1enthalpy[i];
 			}
@@ -5394,14 +5035,29 @@
 
 			matpar->EnthalpyToThermal(&temperature, &waterfraction, enthalpy[iv],pressure[iv]);
-			meltingrate_enthalpy=(basalfriction-(heatflux-geothermalflux[iv]))/((1-waterfraction)*latentheat*rho_ice); // m/yr water equivalent 
+			// -Mb= Fb-(q-q_geo)/((1-w)*L), cf Aschwanden 2012, eq.66
+			heating=(heatflux+basalfriction+geothermalflux[iv]);
+			meltingrate_enthalpy=heating/((1-waterfraction)*latentheat*rho_ice); // m/s water equivalent 
 		}
 
 		/*Update water column, basal meltingrate*/
-		basalmeltingrate[iv]+=meltingrate_enthalpy;
 		this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-		if(reCast<bool,IssmDouble>(dt))
-		 watercolumn[iv]+=dt*meltingrate_enthalpy; 
-		else
-		 watercolumn[iv]+=meltingrate_enthalpy;
+		if(reCast<bool,IssmDouble>(dt)){
+			if(watercolumn[iv]+meltingrate_enthalpy*dt<0.){				
+				melting_overshoot=watercolumn[iv]+meltingrate_enthalpy*dt;
+				lambda=melting_overshoot/(meltingrate_enthalpy*dt); _assert_(lambda>0); _assert_(lambda<1);
+				basalmeltingrate[iv]=(1.-lambda)*meltingrate_enthalpy;
+				watercolumn[iv]=0.;
+				yts=365*24*60*60;
+				enthalpy[iv]+=dt/yts*lambda*heating;
+			}
+			else{
+				basalmeltingrate[iv]=meltingrate_enthalpy;
+				watercolumn[iv]+=dt*meltingrate_enthalpy; 
+			}
+		}
+		else{
+			basalmeltingrate[iv]=meltingrate_enthalpy;
+			watercolumn[iv]+=meltingrate_enthalpy;
+		}	  
 	}  
 	/*feed updated variables back into model*/
@@ -5417,17 +5073,25 @@
 /*FUNCTION Penta::DrainWaterfraction{{{*/
 void Penta::DrainWaterfraction(void){
-    
+
     /*Intermediaries*/
 	bool isenthalpy;
 	IssmDouble waterfraction[NUMVERTICES], temperature[NUMVERTICES];
+	IssmDouble watercolumnbase[NUMVERTICES];
 	IssmDouble enthalpy[NUMVERTICES], pressure[NUMVERTICES]; 
 	IssmDouble latentheat, dt;
+	IssmDouble dw, dwc;
+	Penta *pentabase = NULL;
 
 	/*Check wether enthalpy is activated*/
 	parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
 	if(!isenthalpy) return;       
-
-	GetInputListOnVertices(&enthalpy[0],EnthalpyEnum);
-	GetInputListOnVertices(&pressure[0],PressureEnum);
+	
+	/*get basal element, needed for basal watercolumn*/
+	pentabase=this->GetBasalElement();
+	
+	this->GetInputListOnVertices(&enthalpy[0],EnthalpyEnum);
+	this->GetInputListOnVertices(&pressure[0],PressureEnum);
+	pentabase->GetInputListOnVertices(&watercolumnbase[0], WatercolumnEnum);
+
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
 	latentheat=matpar->GetLatentHeat();
@@ -5435,13 +5099,18 @@
 	for(int iv=0;iv<NUMVERTICES;iv++){ 
 		matpar->EnthalpyToThermal(&temperature[iv],&waterfraction[iv], enthalpy[iv],pressure[iv]); 
-
+		dw=DrainageFunctionWaterfraction(waterfraction[iv], dt);
 		/*drain water fraction & update enthalpy*/
-		waterfraction[iv]-=DrainageFunctionWaterfraction(waterfraction[iv], dt);
+		waterfraction[iv]-=dw;
 		matpar->ThermalToEnthalpy(&enthalpy[iv], temperature[iv], waterfraction[iv], pressure[iv]);        
-	}
+		/*add drained water to watercolumn at base*/
+		dwc=dw*this->IceVolume();
+		watercolumnbase[iv%NUMVERTICES2D]+=dwc;
+	}
+
 	/*feed updated results back into model*/
 	this->inputs->AddInput(new PentaInput(EnthalpyEnum,enthalpy,P1Enum));
 	this->inputs->AddInput(new PentaInput(WaterfractionEnum,waterfraction,P1Enum));
-	// this->inputs->AddInput(new PentaInput(TemperatureEnum,temperature,P1Enum));    // temperature should not change during drainage...
+	pentabase->inputs->AddInput(new PentaInput(WatercolumnEnum, watercolumnbase,P1Enum));
+
 }
 /*}}}*/
@@ -5459,9 +5128,8 @@
 		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
 	}
-	else if(enum_type==MaterialsRheologyZbarEnum){
+	else if(enum_type==DamageDbarEnum){
 		if(!IsOnBed()) return;
-		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
-	}
-
+		input=(Input*)material->inputs->GetInput(DamageDEnum);
+	}
 	else{
 		input=inputs->GetInput(enum_type);
@@ -5482,6 +5150,6 @@
 		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
 	}
-	else if(enum_type==MaterialsRheologyZbarEnum){
-		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	else if(enum_type==DamageDbarEnum){
+		input=(Input*)material->inputs->GetInput(DamageDEnum);
 	}
 	else{
@@ -5504,6 +5172,6 @@
 		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
 	}
-	else if(enum_type==MaterialsRheologyZbarEnum){
-		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	else if(enum_type==DamageDbarEnum){
+		input=(Input*)material->inputs->GetInput(DamageDEnum);
 	}
 	else{
@@ -5517,4 +5185,46 @@
 	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
 	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Penta::ControlToVectors{{{*/
+void Penta::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){
+
+	Input* input=NULL;
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(control_enum==DamageDbarEnum){
+		input=(Input*)material->inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(control_enum);
+	}
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetConnectivityList(&connectivity[0]);
+	this->GetVertexSidList(&sidlist[0]);
+
+	GaussPenta* gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
 
 }/*}}}*/
@@ -5551,8 +5261,5 @@
 		case MaticeEnum:
 			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			break;
-		case MatdamageiceEnum:
-			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 			break;
 		default:
@@ -5567,5 +5274,5 @@
 	/*Delete averaged fields*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 
 	/*clean up and return*/
@@ -5586,5 +5293,4 @@
 	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
 	IssmDouble eps1[3],eps2[3];
-	IssmDouble phi[NUMVERTICES];
 	IssmDouble dphi[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
@@ -5755,5 +5461,4 @@
 ElementVector* Penta::CreatePVectorAdjointHO(void){
 
-
 	/*Nothing to be done if not on surface*/
 	if (!IsOnSurface()) return NULL;
@@ -5783,5 +5488,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
 	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
@@ -5818,5 +5523,5 @@
 		for(resp=0;resp<num_responses;resp++){
 
-			weights_input->GetInputValue(&weight,gauss,resp);
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
 
 			switch(responses[resp]){
@@ -5979,5 +5684,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 	Input* weights_input = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
 	Input* vx_input      = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
@@ -6014,5 +5719,5 @@
 		for(resp=0;resp<num_responses;resp++){
 
-			weights_input->GetInputValue(&weight,gauss,resp);
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
 
 			switch(responses[resp]){
@@ -6160,10 +5865,10 @@
 	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
 
-	int              i,approximation;
-	Tria*            tria=NULL;
+	int   approximation;
+	Tria* tria=NULL;
 
 	/*If on water, skip grad (=0): */
 	if(NoIceInElement())return;
-
+					
 	/*First deal with ∂/∂alpha(KU-F)*/
 	switch(control_type){
@@ -6214,8 +5919,8 @@
 
 	/*Now deal with ∂J/∂alpha*/
-	int        *responses = NULL;
-	int         num_responses,resp;
+	int *responses = NULL;
+	int num_responses,resp;
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 
 	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
@@ -6232,5 +5937,5 @@
 			if(IsOnBed()){
 				tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-				tria->GradjDragGradient(gradient,resp,control_index);
+				tria->GradjDragGradient(gradient,control_index);
 				delete tria->material; delete tria;
 			}
@@ -6239,5 +5944,5 @@
 			if(IsOnBed()){
 				tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-				tria->GradjBGradient(gradient,resp,control_index);
+				tria->GradjBGradient(gradient,control_index);
 				delete tria->material; delete tria;
 			}
@@ -6432,4 +6137,5 @@
 	/*Depth Average B*/
 	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+	this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 
 	/*Collapse element to the base*/
@@ -6440,4 +6146,5 @@
 	/*delete Average B*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 
 } /*}}}*/
@@ -6448,6 +6155,7 @@
 	if (!IsOnBed()) return;
 
-	/*Depth Average B*/
+	/*Depth Average B and D*/
 	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+	this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 
 	/*Collapse element to the base*/
@@ -6458,4 +6166,5 @@
 	/*delete Average B*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 } /*}}}*/
 /*FUNCTION Penta::GradjBbarFS {{{*/
@@ -6465,6 +6174,7 @@
 	if (!IsOnBed()) return;
 
-	/*Depth Average B*/
+	/*Depth Average B and D*/
 	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+	this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 
 	/*Collapse element to the base*/
@@ -6475,4 +6185,5 @@
 	/*delete Average B*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 } /*}}}*/
 /*FUNCTION Penta::InputControlUpdate{{{*/
@@ -6494,7 +6205,7 @@
 			input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
 		}
-		else if(control_type[i]==MaterialsRheologyZbarEnum){
+		else if(control_type[i]==DamageDbarEnum){
 			if (!IsOnBed()) goto cleanup_and_return;
-			input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum); _assert_(input);
+			input=(Input*)material->inputs->GetInput(DamageDEnum); _assert_(input);
 		}
 		else{
@@ -6511,6 +6222,6 @@
 			this->InputExtrude(MaterialsRheologyBEnum,MaterialsEnum);
 		}
-		else if(control_type[i]==MaterialsRheologyZbarEnum){
-			this->InputExtrude(MaterialsRheologyZEnum,MaterialsEnum);
+		else if(control_type[i]==DamageDbarEnum){
+			this->InputExtrude(DamageDEnum,MaterialsEnum);
 		}
 	}
@@ -6528,5 +6239,4 @@
 	int*         pdoflist=NULL;
 	IssmDouble   FSreconditioning;
-	GaussPenta  *gauss;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -6622,5 +6332,5 @@
 /*}}}*/
 /*FUNCTION Penta::SurfaceAverageVelMisfit {{{*/
-IssmDouble Penta::SurfaceAverageVelMisfit(int weight_index){
+IssmDouble Penta::SurfaceAverageVelMisfit(void){
 
 	int    approximation;
@@ -6645,5 +6355,5 @@
 		 * and compute SurfaceAverageVelMisfit*/
 		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-		J=tria->SurfaceAverageVelMisfit(weight_index);
+		J=tria->SurfaceAverageVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6652,5 +6362,5 @@
 
 		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
-		J=tria->SurfaceAverageVelMisfit(weight_index);
+		J=tria->SurfaceAverageVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6659,5 +6369,5 @@
 /*}}}*/
 /*FUNCTION Penta::SurfaceAbsVelMisfit {{{*/
-IssmDouble Penta::SurfaceAbsVelMisfit(int weight_index){
+IssmDouble Penta::SurfaceAbsVelMisfit(void){
 
 	int    approximation;
@@ -6682,5 +6392,5 @@
 		 * and compute SurfaceAbsVelMisfit*/
 		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-		J=tria->SurfaceAbsVelMisfit(weight_index);
+		J=tria->SurfaceAbsVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6689,5 +6399,5 @@
 
 		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
-		J=tria->SurfaceAbsVelMisfit(weight_index);
+		J=tria->SurfaceAbsVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6696,5 +6406,5 @@
 /*}}}*/
 /*FUNCTION Penta::SurfaceLogVelMisfit {{{*/
-IssmDouble Penta::SurfaceLogVelMisfit(int weight_index){
+IssmDouble Penta::SurfaceLogVelMisfit(void){
 
 	int    approximation;
@@ -6719,5 +6429,5 @@
 		 * and compute SurfaceLogVelMisfit*/
 		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-		J=tria->SurfaceLogVelMisfit(weight_index);
+		J=tria->SurfaceLogVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6726,5 +6436,5 @@
 
 		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
-		J=tria->SurfaceLogVelMisfit(weight_index);
+		J=tria->SurfaceLogVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6733,5 +6443,5 @@
 /*}}}*/
 /*FUNCTION Penta::SurfaceLogVxVyMisfit {{{*/
-IssmDouble Penta::SurfaceLogVxVyMisfit(int weight_index){
+IssmDouble Penta::SurfaceLogVxVyMisfit(void){
 
 	IssmDouble J;
@@ -6758,5 +6468,5 @@
 		 * and compute SurfaceLogVxVyMisfit*/
 		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-		J=tria->SurfaceLogVxVyMisfit(weight_index);
+		J=tria->SurfaceLogVxVyMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6765,5 +6475,5 @@
 
 		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
-		J=tria->SurfaceLogVxVyMisfit(weight_index);
+		J=tria->SurfaceLogVxVyMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6772,5 +6482,5 @@
 /*}}}*/
 /*FUNCTION Penta::SurfaceRelVelMisfit {{{*/
-IssmDouble Penta::SurfaceRelVelMisfit(int weight_index){
+IssmDouble Penta::SurfaceRelVelMisfit(void){
 
 	int    approximation;
@@ -6795,5 +6505,5 @@
 		 * and compute SurfaceRelVelMisfit*/
 		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
-		J=tria->SurfaceRelVelMisfit(weight_index);
+		J=tria->SurfaceRelVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6802,5 +6512,5 @@
 
 		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
-		J=tria->SurfaceRelVelMisfit(weight_index);
+		J=tria->SurfaceRelVelMisfit();
 		delete tria->material; delete tria;
 		return J;
@@ -6809,5 +6519,5 @@
 /*}}}*/
 /*FUNCTION Penta::ThicknessAbsGradient{{{*/
-IssmDouble Penta::ThicknessAbsGradient(int weight_index){
+IssmDouble Penta::ThicknessAbsGradient(void){
 
 	_error_("Not implemented yet");
@@ -6815,5 +6525,5 @@
 /*}}}*/
 /*FUNCTION Penta::ThicknessAbsMisfit {{{*/
-IssmDouble Penta::ThicknessAbsMisfit(int weight_index){
+IssmDouble Penta::ThicknessAbsMisfit(void){
 
 	int    approximation;
@@ -6829,5 +6539,5 @@
 
 	tria=(Tria*)SpawnTria(0);
-	J=tria->ThicknessAbsMisfit(weight_index);
+	J=tria->ThicknessAbsMisfit();
 	delete tria->material; delete tria;
 	return J;
@@ -6835,5 +6545,5 @@
 /*}}}*/
 /*FUNCTION Penta::DragCoefficientAbsGradient{{{*/
-IssmDouble Penta::DragCoefficientAbsGradient(int weight_index){
+IssmDouble Penta::DragCoefficientAbsGradient(void){
 
 	IssmDouble J;
@@ -6844,5 +6554,5 @@
 
 	tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1
-	J=tria->DragCoefficientAbsGradient(weight_index);
+	J=tria->DragCoefficientAbsGradient();
 	delete tria->material; delete tria;
 	return J;
@@ -6850,5 +6560,5 @@
 /*}}}*/
 /*FUNCTION Penta::RheologyBbarAbsGradient{{{*/
-IssmDouble Penta::RheologyBbarAbsGradient(int weight_index){
+IssmDouble Penta::RheologyBbarAbsGradient(void){
 
 	IssmDouble J;
@@ -6859,5 +6569,5 @@
 
 	tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1
-	J=tria->RheologyBbarAbsGradient(weight_index);
+	J=tria->RheologyBbarAbsGradient();
 	delete tria->material; delete tria;
 	return J;
@@ -7592,5 +7302,5 @@
 	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
 	delete Ke1; delete Ke2;
-	
+
 	/*Compute HO Matrix with P1 element type\n");*/
 	this->element_type=P1Enum;
@@ -7724,8 +7434,5 @@
 		case MaticeEnum:
 			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			break;
-		case MatdamageiceEnum:
-			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 			break;
 		default:
@@ -7740,5 +7447,5 @@
 	/*Delete averaged fields*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 
 	/*clean up and return*/
@@ -7925,5 +7632,4 @@
 	int         i,j;
 	IssmDouble  Jdet,viscosity;
-	IssmDouble  epsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  B[3][numdof2d];
@@ -8020,5 +7726,4 @@
 
 	/*Intermediaries */
-	int         i,j;
 	int         approximation;
 	IssmDouble  xyz_list[NUMVERTICES][3];
@@ -8065,5 +7770,5 @@
 
 		D_scalar=2*newviscosity*gauss->weight*Jdet;
-		for (i=0;i<5;i++) D[i*5+i]=D_scalar;
+		for(int i=0;i<5;i++) D[i*5+i]=D_scalar;
 
 		TripleMultiply(B,5,numdof,1,
@@ -8221,20 +7926,12 @@
 
 	/*Intermediaries */
-	int        i,j,approximation;
+	int        i,j;
 	IssmDouble Jdet,viscosity,FSreconditioning,diameter,rigidity;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble B[8][24];
-	IssmDouble B_prime[8][24];
-	IssmDouble B_stab[3][NUMVERTICES];
-	IssmDouble D_scalar,D_scalar_stab;
-	IssmDouble D[8][8]={0.0};
-	IssmDouble D_stab[3][3]={0.0};
-	IssmDouble Ke_temp[24][24]={0.0}; //for the six nodes
-	IssmDouble Ke_temp_stab[6][6]={0.0}; //for the six nodes
 	GaussPenta *gauss=NULL;
 
 	/*Stabilization*/
-	bool       stabilization = true;
+	IssmDouble D_scalar;
 	IssmDouble dbasis[3][6];
 	IssmDouble dmu[3];
@@ -8281,5 +7978,4 @@
 
 		D_scalar=gauss->weight*Jdet;
-
 
 		/*Add stabilization*/
@@ -8333,5 +8029,5 @@
 
 	/*Intermediaries */
-	int        i,j,approximation;
+	int        i,approximation;
 	IssmDouble Jdet,viscosity,FSreconditioning,D_scalar;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -8408,6 +8104,4 @@
 	int         analysis_type,approximation;
 	IssmDouble  alpha2,Jdet2d;
-	IssmDouble  FSreconditioning,viscosity;
-	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  xyz_list_tria[NUMVERTICES2D][3];
@@ -8435,5 +8129,4 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
@@ -8452,7 +8145,4 @@
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
 		GetLFS(BFriction,gauss);
-
-		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 
 		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
@@ -8598,6 +8288,5 @@
 
 	/*Intermediaries */
-	int         i,j;
-	int         approximation;
+	int         i,approximation;
 	IssmDouble  viscosity,Jdet;
 	IssmDouble  FSreconditioning;
@@ -8676,5 +8365,4 @@
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  basis[6]; //for the six nodes of the penta
-	Tria*       tria=NULL;
 	Friction*   friction=NULL;
 	GaussPenta  *gauss=NULL;
@@ -8839,5 +8527,4 @@
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  basis[6]; //for the six nodes of the penta
-	Tria*       tria=NULL;
 	Friction*   friction=NULL;
 	GaussPenta  *gauss=NULL;
@@ -9137,5 +8824,4 @@
 
 	/*Intermediaries*/
-	int         i,j;
 	IssmDouble  Jdet;
 	IssmDouble  slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
@@ -9170,5 +8856,5 @@
 		driving_stress_baseline=matpar->GetRhoIce()*matpar->GetG();
 
-		for(i=0;i<numnodes;i++){
+		for(int i=0;i<numnodes;i++){
 			pe->values[i*NDOF2+0]+= -driving_stress_baseline*slope[0]*Jdet*gauss->weight*basis[i];
 			pe->values[i*NDOF2+1]+= -driving_stress_baseline*slope[1]*Jdet*gauss->weight*basis[i];
@@ -9382,15 +9068,11 @@
 	/*Intermediaries*/
 	int        i,j;
-	int        approximation;
 	IssmDouble Jdet,gravity,rho_ice,B,D_scalar_stab,viscosity;
 	IssmDouble forcex,forcey,forcez,diameter,FSreconditioning;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble l1l6[6]; //for the six nodes and the bubble 
-	IssmDouble dh1dh6[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
 	/*Stabilization*/
-	bool       stabilization = true;
 	IssmDouble dbasis[3][6];
 	IssmDouble dmu[3];
@@ -9398,5 +9080,5 @@
 	IssmDouble dnodalbasis[6][6][3];
 	IssmDouble SW[6][4][4];
-	int p,q,ii;
+	int p,ii;
 	int c=3; //index of pressure
 
@@ -9432,5 +9114,4 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsP1(&l1l6[0], gauss);
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
 		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
@@ -9473,5 +9154,5 @@
 
 	/*Intermediaries*/
-	int        i,j;
+	int        i;
 	int        approximation;
 	IssmDouble Jdet,gravity,rho_ice;
@@ -9786,8 +9467,5 @@
 		case MaticeEnum:
 			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			break;
-		case MatdamageiceEnum:
-			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
-			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum,MaterialsEnum);
 			break;
 		default:
@@ -9802,5 +9480,5 @@
 	/*Delete averaged inputs*/
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+	this->material->inputs->DeleteInput(DamageDbarEnum);
 
 	/*clean up and return*/
@@ -9810,7 +9488,4 @@
 /*FUNCTION Penta::CreateJacobianStressbalanceHO{{{*/
 ElementMatrix* Penta::CreateJacobianStressbalanceHO(void){
-
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
 
 	/*Intermediaries */
@@ -9876,5 +9551,5 @@
 
 	/*Intermediaries */
-	int        i,j,approximation;
+	int        i,j;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble Jdet;
@@ -10032,37 +9707,4 @@
 		values[i*NDOF2+0]=vx;
 		values[i*NDOF2+1]=vy;
-	}
-
-	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<int>(doflist);
-}
-/*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsStressbalanceVert{{{*/
-void  Penta::GetSolutionFromInputsStressbalanceVert(Vector<IssmDouble>* solution){
-
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble       vz;
-	IssmDouble       values[numdof];
-	GaussPenta*  gauss=NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	/*P1 element only for now*/
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
-		/*Recover vz */
-		gauss->GaussVertex(i);
-		vz_input->GetInputValue(&vz,gauss);
-		values[i]=vz;
 	}
 
@@ -10412,14 +10054,13 @@
 void  Penta::InputUpdateFromSolutionStressbalanceSSAFS(IssmDouble* solution){
 
-	const int    numdofm=NDOF2*NUMVERTICES;
-	const int    numdofs=NDOF3*NUMVERTICES;
-	const int    numdof2d=NDOF2*NUMVERTICES2D;
-	const int    numdofpressure=NDOF1*NUMVERTICES;
+	const int    numdofSSA = NDOF2*NUMVERTICES;
+	const int    numdof2d  = NDOF2*NUMVERTICES2D;
+	const int    numdofFSv = NDOF3*NUMVERTICES;
+	const int    numdofFSp = NDOF1*NUMVERTICES;
 
 	int     i;
 	IssmDouble  FSreconditioning;
-	IssmDouble  SSA_values[numdofm];
-	IssmDouble  FS_values[numdofs];
-	IssmDouble  Pressure_values[numdofs];
+	IssmDouble  SSA_values[numdofSSA];
+	IssmDouble  FS_values[numdofFSv+numdofFSp];
 	IssmDouble  vx[NUMVERTICES];
 	IssmDouble  vy[NUMVERTICES];
@@ -10430,8 +10071,13 @@
 	IssmDouble  pressure[NUMVERTICES];
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	int*    doflistm        = NULL;
-	int*    doflists        = NULL;
-	int*    doflistpressure = NULL;
-	Penta   *penta          = NULL;
+	int   *doflistSSA = NULL;
+	int   *doflistFSv = NULL;
+	int   *doflistFSp = NULL;
+	Penta *penta      = NULL;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(2*NUMVERTICES);
+	for(i=0;i<NUMVERTICES;i++) cs_list[i]             = XYZEnum;
+	for(i=0;i<NUMVERTICES;i++) cs_list[NUMVERTICES+i] = PressureEnum;
 
 	/*OK, we have to add results of this element for SSA 
@@ -10440,7 +10086,7 @@
 
 	/*Get dof listof this element (SSA dofs) and of the penta at base (SSA dofs): */
-	penta->GetDofList(&doflistm,SSAApproximationEnum,GsetEnum);
-	GetDofList(&doflists,FSvelocityEnum,GsetEnum);
-	GetDofListPressure(&doflistpressure,GsetEnum);
+	penta->GetDofList(&doflistSSA,SSAApproximationEnum,GsetEnum);
+	GetDofList(&doflistFSv,FSvelocityEnum,GsetEnum);
+	GetDofListPressure(&doflistFSp,GsetEnum);
 	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 
@@ -10450,25 +10096,25 @@
 	/*Use the dof list to index into the solution vector: */
 	for(i=0;i<numdof2d;i++){
-		SSA_values[i]=solution[doflistm[i]];
-		SSA_values[i+numdof2d]=solution[doflistm[i]];
-	}
-	for(i=0;i<numdofs;i++)FS_values[i]=solution[doflists[i]];
-	for(i=0;i<numdofpressure;i++) Pressure_values[i]=solution[doflistpressure[i]];
+		SSA_values[i]=solution[doflistSSA[i]];
+		SSA_values[i+numdof2d]=solution[doflistSSA[i]];
+	}
+	for(i=0;i<numdofFSv;i++) FS_values[i]=solution[doflistFSv[i]];
+	for(i=0;i<numdofFSp;i++) FS_values[numdofFSv+i]=solution[doflistFSp[i]];
 
 	/*Transform solution in Cartesian Space*/
 	TransformSolutionCoord(&SSA_values[0],this->nodes,NUMVERTICES,XYEnum);
-	TransformSolutionCoord(&FS_values[0],this->nodes,NUMVERTICES,XYZEnum);
+	TransformSolutionCoord(&FS_values[0],this->nodes,2*NUMVERTICES,cs_list);
 
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
 	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=FS_values[i*NDOF3+0]+SSA_values[i*NDOF2+0];
-		vy[i]=FS_values[i*NDOF3+1]+SSA_values[i*NDOF2+1];
-		vzFS[i]=FS_values[i*NDOF3+2];
-		pressure[i]=Pressure_values[i*NDOF1]*FSreconditioning;
+		vx[i]       = FS_values[i*NDOF3+0]+SSA_values[i*NDOF2+0];
+		vy[i]       = FS_values[i*NDOF3+1]+SSA_values[i*NDOF2+1];
+		vzFS[i]     = FS_values[i*NDOF3+2];
+		pressure[i] = FS_values[NUMVERTICES*NDOF3+i]*FSreconditioning;
 
 		/*Check solution*/
 		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzFS[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i]))     _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
@@ -10488,6 +10134,6 @@
 	/*Now Compute vel*/
 	for(i=0;i<NUMVERTICES;i++) {
-		vz[i]=vzSSA[i]+vzFS[i];
-		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+		vz[i]  = vzSSA[i]+vzFS[i];
+		vel[i] = sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 	}
 
@@ -10508,7 +10154,8 @@
 
 	/*Free ressources:*/
-	xDelete<int>(doflistm);
-	xDelete<int>(doflists);
-	xDelete<int>(doflistpressure);
+	xDelete<int>(doflistSSA);
+	xDelete<int>(doflistFSv);
+	xDelete<int>(doflistFSp);
+	xDelete<int>(cs_list);
 }
 /*}}}*/
@@ -10670,12 +10317,11 @@
 void  Penta::InputUpdateFromSolutionStressbalanceHOFS(IssmDouble* solution){
 
-	const int    numdofp=NDOF2*NUMVERTICES;
-	const int    numdofs=NDOF3*NUMVERTICES;
-	const int    numdofpressure=NDOF1*NUMVERTICES;
+	const int    numdofHO  = NDOF2*NUMVERTICES;
+	const int    numdofFSv = NDOF3*NUMVERTICES;
+	const int    numdofFSp = NDOF1*NUMVERTICES;
 
 	int        i;
-	IssmDouble HO_values[numdofp];
-	IssmDouble FS_values[numdofs];
-	IssmDouble Pressure_values[numdofpressure];
+	IssmDouble HO_values[numdofHO];
+	IssmDouble FS_values[numdofFSv+numdofFSp];
 	IssmDouble vx[NUMVERTICES];
 	IssmDouble vy[NUMVERTICES];
@@ -10687,17 +10333,17 @@
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble FSreconditioning;
-	int*       doflistp        = NULL;
-	int*       doflists        = NULL;
-	int*       doflistpressure = NULL;
-	Penta      *penta          = NULL;
-
-	/*OK, we have to add results of this element for HO 
-	 * and results from the penta at base for SSA. Now recover results*/
-	penta=GetBasalElement();
+	int*       doflistHO        = NULL;
+	int*       doflistFSv        = NULL;
+	int*       doflistFSp = NULL;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(2*NUMVERTICES);
+	for(i=0;i<NUMVERTICES;i++) cs_list[i]             = XYZEnum;
+	for(i=0;i<NUMVERTICES;i++) cs_list[NUMVERTICES+i] = PressureEnum;
 
 	/*Get dof listof this element (HO dofs) and of the penta at base (SSA dofs): */
-	GetDofList(&doflistp,HOApproximationEnum,GsetEnum);
-	GetDofList(&doflists,FSvelocityEnum,GsetEnum);
-	GetDofListPressure(&doflistpressure,GsetEnum);
+	GetDofList(&doflistHO,HOApproximationEnum,GsetEnum);
+	GetDofList(&doflistFSv,FSvelocityEnum,GsetEnum);
+	GetDofListPressure(&doflistFSp,GsetEnum);
 	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 
@@ -10706,23 +10352,23 @@
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdofp;i++) HO_values[i]=solution[doflistp[i]];
-	for(i=0;i<numdofs;i++) FS_values[i]=solution[doflists[i]];
-	for(i=0;i<numdofpressure;i++) Pressure_values[i]=solution[doflistpressure[i]];
+	for(i=0;i<numdofHO;i++)  HO_values[i]=solution[doflistHO[i]];
+	for(i=0;i<numdofFSv;i++) FS_values[i]=solution[doflistFSv[i]];
+	for(i=0;i<numdofFSp;i++) FS_values[numdofFSv+i]=solution[doflistFSp[i]];
 
 	/*Transform solution in Cartesian Space*/
 	TransformSolutionCoord(&HO_values[0],this->nodes,NUMVERTICES,XYEnum);
-	TransformSolutionCoord(&FS_values[0],this->nodes,NUMVERTICES,XYZEnum);
+	TransformSolutionCoord(&FS_values[0],this->nodes,2*NUMVERTICES,cs_list);
 
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
 	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=FS_values[i*NDOF3+0]+HO_values[i*NDOF2+0];
-		vy[i]=FS_values[i*NDOF3+1]+HO_values[i*NDOF2+1];
-		vzFS[i]=FS_values[i*NDOF3+2];
-		pressure[i]=Pressure_values[i*NDOF1]*FSreconditioning;
+		vx[i]       = FS_values[i*NDOF3+0]+HO_values[i*NDOF2+0];
+		vy[i]       = FS_values[i*NDOF3+1]+HO_values[i*NDOF2+1];
+		vzFS[i]     = FS_values[i*NDOF3+2];
+		pressure[i] = FS_values[NUMVERTICES*NDOF3+i]*FSreconditioning;
 
 		/*Check solution*/
 		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzFS[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i]))     _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
@@ -10742,6 +10388,6 @@
 	/*Now Compute vel*/
 	for(i=0;i<NUMVERTICES;i++) {
-		vz[i]=vzHO[i]+vzFS[i];
-		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+		vz[i]  = vzHO[i]+vzFS[i];
+		vel[i] = sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 	}
 
@@ -10762,7 +10408,8 @@
 
 	/*Free ressources:*/
-	xDelete<int>(doflistp);
-	xDelete<int>(doflists);
-	xDelete<int>(doflistpressure);
+	xDelete<int>(doflistHO);
+	xDelete<int>(doflistFSv);
+	xDelete<int>(doflistFSp);
+	xDelete<int>(cs_list);
 }
 /*}}}*/
@@ -10942,5 +10589,4 @@
 	int*         pdoflist=NULL;
 	IssmDouble   FSreconditioning;
-	GaussPenta  *gauss;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -10951,11 +10597,15 @@
 
 	/*Initialize values*/
-	IssmDouble* vvalues  = xNew<IssmDouble>(vnumdof);
-	IssmDouble* pvalues  = xNew<IssmDouble>(pnumdof);
+	IssmDouble* values   = xNew<IssmDouble>(vnumdof+pnumdof);
 	IssmDouble* vx       = xNew<IssmDouble>(vnumnodes);
 	IssmDouble* vy       = xNew<IssmDouble>(vnumnodes);
 	IssmDouble* vz       = xNew<IssmDouble>(vnumnodes);
 	IssmDouble* vel      = xNew<IssmDouble>(vnumnodes);
-	IssmDouble* pressure = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(pnumnodes);
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
 
 	/*Get dof list: */
@@ -10964,15 +10614,15 @@
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<vnumdof;i++) vvalues[i]=solution[vdoflist[i]];
-	for(i=0;i<pnumdof;i++) pvalues[i]=solution[pdoflist[i]];
+	for(i=0;i<vnumdof;i++) values[i]        =solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) values[vnumdof+i]=solution[pdoflist[i]];
 
 	/*Transform solution in Cartesian Space*/
-	TransformSolutionCoord(&vvalues[0],nodes,vnumnodes,XYZEnum);
+	TransformSolutionCoord(&values[0],nodes,vnumnodes+pnumdof,cs_list);
 
 	/*Ok, we have vx and vy in values, fill in all arrays: */
 	for(i=0;i<vnumnodes;i++){
-		vx[i] = vvalues[i*NDOF3+0];
-		vy[i] = vvalues[i*NDOF3+1];
-		vz[i] = vvalues[i*NDOF3+2];
+		vx[i] = values[i*NDOF3+0];
+		vy[i] = values[i*NDOF3+1];
+		vz[i] = values[i*NDOF3+2];
 		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
@@ -10980,5 +10630,5 @@
 	}
 	for(i=0;i<pnumnodes;i++){
-		pressure[i] = pvalues[i];
+		pressure[i] = values[vnumdof+i];
 		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
@@ -10986,6 +10636,6 @@
 	/*Recondition pressure and compute vel: */
 	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	for(i=0;i<pnumnodes;i++) pressure[i]=pressure[i]*FSreconditioning;
-	for(i=0;i<vnumnodes;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	for(i = 0;i<pnumnodes;i++) pressure[i] = pressure[i]*FSreconditioning;
+	for(i = 0;i<vnumnodes;i++) vel[i]      = sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 
 	/*Now, we have to move the previous inputs  to old 
@@ -11009,8 +10659,8 @@
 	xDelete<IssmDouble>(vy);
 	xDelete<IssmDouble>(vx);
-	xDelete<IssmDouble>(vvalues);
-	xDelete<IssmDouble>(pvalues);
+	xDelete<IssmDouble>(values);
 	xDelete<int>(vdoflist);
 	xDelete<int>(pdoflist);
+	xDelete<int>(cs_list);
 }
 /*}}}*/
@@ -11278,5 +10928,4 @@
 	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
 	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];
-	bool       grounded[NUMVERTICES],floating[NUMVERTICES];
 
 	if(!IsOnBed()) return;
@@ -11303,6 +10952,4 @@
 				b[i]        = r[i];
 				s[i]        = b[i]+h[i];
-				floating[i] = false;
-				grounded[i] = true;
 			}
 		}
@@ -11316,12 +10963,8 @@
 					s[i]        = (1-density)*h[i];
 					b[i]        = -density*h[i];
-					floating[i] = true;
-					grounded[i] = false;
 				}
 				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
 					s[i]        = (1-density)*h[i];
 					b[i]        = -density*h[i];
-					floating[i] = true;
-					grounded[i] = false;
 				}
 				else{
Index: /issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Penta.h	(revision 16560)
@@ -43,5 +43,4 @@
 		Parameters  *parameters;                  //pointer to solution parameters
 		Inputs      *inputs;
-		Results     *results;
 
 		/*Penta constructors and destructor: {{{*/
@@ -82,5 +81,4 @@
 		void   CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
 		void   Delta18oParameterization(void);
-		void   DeleteResults(void);
 		int    GetNodeIndex(Node* node);
 		void   GetNodesSidList(int* sidlist);
@@ -90,19 +88,13 @@
 		IssmDouble GetZcoord(GaussPenta* gauss);
 		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int name_enum);
-		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int name_enum,int interp);
 
 		int    Sid();
-		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
-		void   InputCreate(IssmDouble scalar,int name,int code);
-		void   InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void   InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
 		void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
 		void   InputDuplicate(int original_enum,int new_enum);
 		void   InputScale(int enum_type,IssmDouble scale_factor);
 
-		void   InputToResult(int enum_type,int step,IssmDouble time);
-		void   RequestedOutput(int output_enum,int step,IssmDouble time);
-		void   ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results);
-		void   PatchFill(int* pcount, Patch* patch);
-		void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
+		void   ResultInterpolation(int* pinterpolation,int output_enum);
+		void   ResultToVector(Vector<IssmPDouble>* vector,int output_enum);
 		void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
 		void   ResetCoordinateSystem(void);
@@ -117,4 +109,5 @@
 		void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
 		IssmDouble IceVolume(void);
+		IssmDouble IceVolumeAboveFloatation(void);
 		IssmDouble TotalSmb(void);
 		void   MinVel(IssmDouble* pminvel);
@@ -123,4 +116,5 @@
 		void   MinVz(IssmDouble* pminvz);
 		IssmDouble MassFlux(IssmDouble* segment);
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
 		void   MaxAbsVx(IssmDouble* pmaxabsvx);
 		void   MaxAbsVy(IssmDouble* pmaxabsvy);
@@ -138,5 +132,5 @@
 
 		#ifdef _HAVE_CONTROL_
-		IssmDouble DragCoefficientAbsGradient(int weight_index);
+		IssmDouble DragCoefficientAbsGradient(void);
 		void   GradientIndexing(int* indexing,int control_index);
 		void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
@@ -152,15 +146,16 @@
 		void   ControlInputScaleGradient(int enum_type,IssmDouble scale);
 		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
-		IssmDouble RheologyBbarAbsGradient(int weight_index);
-		IssmDouble ThicknessAbsMisfit(     int weight_index);
-		IssmDouble SurfaceAbsVelMisfit(    int weight_index);
-		IssmDouble SurfaceRelVelMisfit(    int weight_index);
-		IssmDouble SurfaceLogVelMisfit(    int weight_index);
-		IssmDouble SurfaceLogVxVyMisfit(   int weight_index);
-		IssmDouble SurfaceAverageVelMisfit(int weight_index);
-		IssmDouble ThicknessAbsGradient(int weight_index);
-		IssmDouble ThicknessAlongGradient( int weight_index){_error_("not supported");};
-		IssmDouble ThicknessAcrossGradient(int weight_index){_error_("not supported");};
-		IssmDouble BalancethicknessMisfit(int weight_index){_error_("not supported");};
+		void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
+		IssmDouble RheologyBbarAbsGradient(void);
+		IssmDouble ThicknessAbsMisfit(void);
+		IssmDouble SurfaceAbsVelMisfit(void);
+		IssmDouble SurfaceRelVelMisfit(void);
+		IssmDouble SurfaceLogVelMisfit(void);
+		IssmDouble SurfaceLogVxVyMisfit(void);
+		IssmDouble SurfaceAverageVelMisfit(void);
+		IssmDouble ThicknessAbsGradient(void);
+		IssmDouble ThicknessAlongGradient(void){_error_("not supported");};
+		IssmDouble ThicknessAcrossGradient(void){_error_("not supported");};
+		IssmDouble BalancethicknessMisfit(void){_error_("not supported");};
 		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
 		#endif
@@ -184,5 +179,5 @@
 		ElementVector* CreatePVectorFreeSurfaceTop(void);
 		ElementVector* CreatePVectorFreeSurfaceBase(void);
-		ElementVector* CreatePVectorSlope(void);
+		ElementVector* CreatePVectorL2ProjectionBase(void);
 		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble xyz_zero[3][3],IssmDouble xyz_list[6][3],int numpoints);
 		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
@@ -201,7 +196,7 @@
 		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
 		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void           GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype);
 		void	         GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
 		void           GetQuadNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
-		void	         GetSolutionFromInputsEnthalpy(Vector<IssmDouble>* solutiong);
 		IssmDouble     GetStabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa);
 		void           GetStrainRate3dHO(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input);
@@ -224,6 +219,4 @@
 		bool           NoIceInElement(void); 
 		IssmDouble     MinEdgeLength(IssmDouble xyz_list[6][3]);
-		void	         ReduceMatrixFS(IssmDouble* Ke_reduced, IssmDouble* Ke_temp);
-		void	         ReduceVectorFS(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp);
 		void	         SetClone(int* minranks);
 		Tria*	         SpawnTria(int location);
@@ -280,5 +273,4 @@
 		void	         GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solutiong);
 		void	         GetSolutionFromInputsStressbalanceFS(Vector<IssmDouble>* solutiong);
-		void	         GetSolutionFromInputsStressbalanceVert(Vector<IssmDouble>* solutiong);
 		ElementVector* CreatePVectorCouplingSSAFS(void);
 		ElementVector* CreatePVectorCouplingSSAFSViscous(void);
@@ -333,4 +325,6 @@
 		#endif
 
+		void           UpdateConstraintsExtrudeFromBase(void){_error_("not implemented yet");};
+		void           UpdateConstraintsExtrudeFromTop(void){_error_("not implemented yet");};
 		#ifdef _HAVE_THERMAL_
 		ElementMatrix* CreateKMatrixEnthalpy(void);
@@ -350,8 +344,7 @@
 		ElementVector* CreatePVectorThermalShelf(void);
 		ElementVector* CreatePVectorThermalSheet(void);
-		void	         GetSolutionFromInputsThermal(Vector<IssmDouble>* solutiong);
 		void           InputUpdateFromSolutionThermal(IssmDouble* solutiong);
 		void           InputUpdateFromSolutionEnthalpy(IssmDouble* solutiong);
-		void           UpdateThermalBasalConstraints(void);
+		void           UpdateBasalConstraintsEnthalpy(void);
 		void           ComputeBasalMeltingrate(void);
 		void           DrainWaterfraction(void);
Index: /issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 16560)
@@ -334,7 +334,7 @@
 	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
 	 * For node i, Bvi can be expressed in the actual coordinate system
-	 * by: 	   Bvi=[ dh/dx          0              0      ]
+	 * by: 	   Bvi=[ dh/dx          0             0      ]
 	 *					[   0           dh/dy           0      ]
-	 *					[   0             0           dh/dy    ]
+	 *					[   0             0           dh/dz    ]
 	 *					[ 1/2*dh/dy    1/2*dh/dx        0      ]
 	 *					[ 1/2*dh/dz       0         1/2*dh/dx  ]
@@ -846,7 +846,6 @@
 	 * where h is the interpolation function for node i.
 	 */
-	int i;
-	int num_dof=4;
-
+
+	int        num_dof=4;
 	IssmDouble L1L2l3[NUMNODESP1_2d];
 	IssmDouble dbasis[3][NUMNODESP1];
@@ -1227,5 +1226,5 @@
 	if(*Jdet<0) _error_("negative jacobian determinant!");
 }
-/*}}}*
+/*}}}*/
 /*FUNCTION PentaRef::GetSegmentJacobianDeterminant{{{*/
 void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
@@ -1893,24 +1892,4 @@
 	dbasis[NUMNODESP1*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
 	dbasis[NUMNODESP1*2+5]=0.5*gauss->coord3;
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetQuadNodalFunctions {{{*/
-void PentaRef::GetQuadNodalFunctions(IssmDouble* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4){
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	IssmDouble BasisFunctions[6];
-
-	GetNodalFunctionsP1(&BasisFunctions[0],gauss);
-
-	_assert_(index1>=0 && index1<6);
-	_assert_(index2>=0 && index2<6);
-	_assert_(index3>=0 && index3<6);
-	_assert_(index4>=0 && index4<6);
-
-	l1l4[0]=BasisFunctions[index1];
-	l1l4[1]=BasisFunctions[index2];
-	l1l4[2]=BasisFunctions[index3];
-	l1l4[3]=BasisFunctions[index4];
-
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 16560)
@@ -35,5 +35,4 @@
 		void GetNodalFunctionsP1DerivativesReference(IssmDouble* dl1dl6,GaussPenta* gauss);
 		void GetNodalFunctionsMINIDerivativesReference(IssmDouble* dl1dl7,GaussPenta* gauss);
-		void GetQuadNodalFunctions(IssmDouble* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4);
 		void GetQuadJacobianDeterminant(IssmDouble*  Jdet, IssmDouble xyz_list[4][3],GaussPenta* gauss);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussPenta* gauss);
Index: /issm/trunk/src/c/classes/Elements/Seg.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 16560)
+++ /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 16560)
@@ -0,0 +1,490 @@
+/*!\file Seg.cpp
+ * \brief: implementation of the Segment object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+/*Constructors/destructor/copy*/
+/*FUNCTION Seg::Seg(){{{*/
+Seg::Seg(){
+	this->nodes      = NULL;
+	this->vertices   = NULL;
+	this->material   = NULL;
+	this->matpar     = NULL;
+	this->inputs     = NULL;
+	this->parameters = NULL;
+}
+/*}}}*/
+/*FUNCTION Seg::Seg(int id, int sid,int index, IoModel* iomodel,int nummodels){{{*/
+Seg::Seg(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)
+		:SegRef(nummodels),ElementHook(nummodels,index+1,2,iomodel){
+
+			/*id: */
+			this->id  = seg_id;
+			this->sid = seg_sid;
+
+			//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+			this->parameters = NULL;
+
+			/*intialize inputs: */
+			this->inputs  = new Inputs();
+
+			/*initialize pointers:*/
+			this->nodes    = NULL;
+			this->vertices = NULL;
+			this->material = NULL;
+			this->matpar   = NULL;
+
+		}
+/*}}}*/
+/*FUNCTION Seg::~Seg(){{{*/
+Seg::~Seg(){
+	delete inputs;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Seg::copy {{{*/
+Object* Seg::copy() {
+	_error_("not implemented yet");
+}
+/*}}}*/
+
+/*FUNCTION Seg::Echo{{{*/
+void Seg::Echo(void){
+	_printf_("Seg:\n");
+	_printf_("   id: " << id << "\n");
+	if(nodes){
+		nodes[0]->Echo();
+		nodes[1]->Echo();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->Echo();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->Echo();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->Echo();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->Echo();
+	else _printf_("inputs=NULL\n");
+}
+/*}}}*/
+/*FUNCTION Seg::DeepEcho{{{*/
+void Seg::DeepEcho(void){
+
+	_printf_("Seg:\n");
+	_printf_("   id: " << id << "\n");
+	if(nodes){
+		nodes[0]->DeepEcho();
+		nodes[1]->DeepEcho();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->DeepEcho();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->DeepEcho();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->DeepEcho();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->DeepEcho();
+	else _printf_("inputs=NULL\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Seg::ObjectEnum{{{*/
+int Seg::ObjectEnum(void){
+
+	return SegEnum;
+
+}
+/*}}}*/
+/*FUNCTION Seg::Id {{{*/
+int    Seg::Id(){
+
+	return id;
+
+}
+/*}}}*/
+
+/*FUNCTION Seg::GetSize{{{*/
+IssmDouble Seg::GetSize(void){
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble x1,y1,x2,y2;
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x1=xyz_list[0][0]; y1=xyz_list[0][1];
+	x2=xyz_list[1][0]; y2=xyz_list[1][1];
+
+	return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
+}
+/*}}}*/
+/*FUNCTION Seg::CreateKMatrixFreeSurfaceTop {{{*/
+ElementMatrix* Seg::CreateKMatrixFreeSurfaceTop(void){
+
+	/*Intermediaries */
+	int        stabilization;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vx,vel;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(1*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(1*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	h=this->GetSize();
+
+	/* Start  looping on the number of gaussian points: */
+	GaussSeg *gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetNodalFunctions(B,gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
+
+		D_scalar=dt*gauss->weight*Jdet*vx;
+		TripleMultiply(B,1,numnodes,1,
+					&D_scalar,1,1,0,
+					Bprime,1,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=fabs(vx)+1.e-8;
+			D_scalar=dt*gauss->weight*Jdet*h/(2.*vel)*vx;
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vx_input->GetInputAverage(&vx);
+			D_scalar=dt*gauss->weight*Jdet*h/2.*fabs(vx);
+		}
+		if(stabilization==1 || stabilization==2){
+			TripleMultiply(Bprime,1,numnodes,1,
+						&D_scalar,1,1,0,
+						Bprime,1,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Seg::CreateKMatrixFreeSurfaceBase {{{*/
+ElementMatrix* Seg::CreateKMatrixFreeSurfaceBase(void){
+
+	/*Intermediaries */
+	int        stabilization;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vx,vel;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(1*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(1*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	h=this->GetSize();
+
+	/* Start  looping on the number of gaussian points: */
+	GaussSeg *gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetNodalFunctions(B,gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
+
+		D_scalar=dt*gauss->weight*Jdet*vx;
+		TripleMultiply(B,1,numnodes,1,
+					&D_scalar,1,1,0,
+					Bprime,1,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=fabs(vx)+1.e-8;
+			D_scalar=dt*gauss->weight*Jdet*h/(2.*vel)*vx;
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vx_input->GetInputAverage(&vx);
+			D_scalar=dt*gauss->weight*Jdet*h/2.*fabs(vx);
+		}
+		if(stabilization==1 || stabilization==2){
+			TripleMultiply(Bprime,1,numnodes,1,
+						&D_scalar,1,1,0,
+						Bprime,1,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Seg::CreateMassMatrix {{{*/
+ElementMatrix* Seg::CreateMassMatrix(void){
+
+	/* Intermediaries */
+	IssmDouble  D,Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke    = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/* Start looping on the number of gaussian points: */
+	GaussSeg* gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetNodalFunctions(basis,gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Seg::CreatePVectorL2Projection {{{*/
+ElementVector* Seg::CreatePVectorL2Projection(void){
+
+	/*Intermediaries */
+	int        i,input_enum;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble value;
+	Input*     input2 = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&input_enum,InputToL2ProjectEnum);
+	Input* input = inputs->GetInput(input_enum);
+	if(!input){
+		switch(input_enum){
+			case SurfaceSlopeXEnum: input2 = inputs->GetInput(SurfaceEnum); _assert_(input2); break;
+			case BedSlopeXEnum:     input2 = inputs->GetInput(BedEnum);     _assert_(input2); break;
+			default: _error_("input not found in element");
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	GaussSeg* gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		if(input){
+			input->GetInputValue(&value,gauss);
+		}
+		else{
+			input2->GetInputDerivativeValue(&value,&xyz_list[0][0],gauss);
+		}
+
+		for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*value*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Seg::CreatePVectorFreeSurfaceTop {{{*/
+ElementVector* Seg::CreatePVectorFreeSurfaceTop(void){
+
+	/*Intermediaries */
+	IssmDouble Jdet,dt;
+	IssmDouble ms,surface,vy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vy_input     = inputs->GetInput(VyEnum);                         _assert_(vy_input);
+	Input* ms_input     = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* surface_input= inputs->GetInput(SurfaceEnum);                    _assert_(surface_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussSeg* gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vy_input->GetInputValue(&vy,gauss);
+		ms_input->GetInputValue(&ms,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(surface + dt*ms + dt*vy)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Seg::CreatePVectorFreeSurfaceBase {{{*/
+ElementVector* Seg::CreatePVectorFreeSurfaceBase(void){
+
+	/*Intermediaries */
+	IssmDouble Jdet,dt;
+	IssmDouble mb,mb_correction,bed,vy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vy_input            = inputs->GetInput(VyEnum);                         _assert_(vy_input);
+	Input* mb_input            = inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* mb_correction_input = inputs->GetInput(BasalforcingsMeltingRateCorrectionEnum);
+	Input* bed_input           = inputs->GetInput(BedEnum);                        _assert_(bed_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussSeg* gauss=new GaussSeg(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vy_input->GetInputValue(&vy,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		bed_input->GetInputValue(&bed,gauss);
+		if(mb_correction_input)
+		 mb_correction_input->GetInputValue(&mb_correction,gauss);
+		else
+		 mb_correction=0.;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb-mb_correction) + dt*vy)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Seg.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.h	(revision 16560)
+++ /issm/trunk/src/c/classes/Elements/Seg.h	(revision 16560)
@@ -0,0 +1,197 @@
+/*! \file Seg.h 
+ *  \brief: header file for seg object
+ */
+
+#ifndef _SEG_H_
+#define _SEG_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./SegRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Results;
+class Node;
+class Material;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+class Vertex;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Seg: public Element,public ElementHook,public SegRef{
+
+	public:
+
+		int          id;
+		int          sid;
+
+		Node       **nodes;                       // nodes
+		Vertex     **vertices;                    // 3 vertices
+		Material    *material;                    // 1 material ice
+		Matpar      *matpar;                      // 1 material parameter
+
+		Parameters  *parameters;                  //pointer to solution parameters
+		Inputs      *inputs;
+
+		/*Seg constructors, destructors {{{*/
+		Seg();
+		Seg(int seg_id,int seg_sid,int i, IoModel* iomodel,int nummodels);
+		~Seg();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromSolution(IssmDouble* solutiong){_error_("not implemented yet");};
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
+#endif
+		void  InputUpdateFromConstant(IssmDouble constant, int name){_error_("not implemented yet");};
+		void  InputUpdateFromConstant(int constant, int name){_error_("not implemented yet");};
+		void  InputUpdateFromConstant(bool constant, int name){_error_("not implemented yet");};
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
+		void        ComputeStrainRate(Vector<IssmDouble>* eps){_error_("not implemented yet");};
+		void        ComputeStressTensor(){_error_("not implemented yet");};
+		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){_error_("not implemented yet");};
+		void        CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){_error_("not implemented yet");};
+		void        CreateDVector(Vector<IssmDouble>* df){_error_("not implemented yet");};
+		void        CreatePVector(Vector<IssmDouble>* pf){_error_("not implemented yet");};
+		ElementVector* CreatePVectorL2Projection(void);
+		void        CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("not implemented yet");};
+		void        Delta18oParameterization(void){_error_("not implemented yet");};
+		int         GetNodeIndex(Node* node){_error_("not implemented yet");};
+		void        GetNodesSidList(int* sidlist){_error_("not implemented yet");};
+		void        GetNodesLidList(int* lidlist){_error_("not implemented yet");};
+		int         GetNumberOfNodes(void){_error_("not implemented yet");};
+		int         Sid(){_error_("not implemented yet");};
+		bool        IsOnBed(){_error_("not implemented yet");};
+		bool        IsFloating(){_error_("not implemented yet");};
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
+		bool        NoIceInElement(){_error_("not implemented yet");};
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype){_error_("not implemented yet");};
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){_error_("not implemented yet");};
+		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
+		void           GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
+		#ifdef _HAVE_THERMAL_
+		void UpdateBasalConstraintsEnthalpy(void){_error_("not implemented yet");};
+		void ComputeBasalMeltingrate(void){_error_("not implemented yet");};
+		void DrainWaterfraction(void){_error_("not implemented yet");};
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+		void    GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode){_error_("not implemented yet");};
+		void    GetHydrologyTransfer(Vector<IssmDouble>* transfer){_error_("not implemented yet");};
+		void    HydrologyEPLGetActive(Vector<IssmDouble>* active_vec){_error_("not implemented yet");};
+		void    HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask){_error_("not implemented yet");};
+		#endif
+		void        GetSolutionFromInputs(Vector<IssmDouble>* solution){_error_("not implemented yet");};
+		void        GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum){_error_("not implemented yet");};
+		void        InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){_error_("not implemented yet");};
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum){_error_("not implemented yet");};
+		void        InputDuplicate(int original_enum,int new_enum){_error_("not implemented yet");};
+		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){_error_("not implemented yet");};
+		void        ResultInterpolation(int* pinterpolation,int output_enum){_error_("not implemented");};
+		void        ResultToVector(Vector<IssmPDouble>* vector,int output_enum){_error_("not implemented");};
+		void        ResetCoordinateSystem(void){_error_("not implemented yet");};
+		void	      SmbGradients(){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
+		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
+		void UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
+		void UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
+
+#ifdef _HAVE_RESPONSES_
+		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
+		IssmDouble IceVolume(void){_error_("not implemented yet");};
+		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		IssmDouble TotalSmb(void){_error_("not implemented yet");};
+		void       MinVel(IssmDouble* pminvel){_error_("not implemented yet");};
+		void       MinVx(IssmDouble* pminvx){_error_("not implemented yet");};
+		void       MinVy(IssmDouble* pminvy){_error_("not implemented yet");};
+		void       MinVz(IssmDouble* pminvz){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
+		void       MaxAbsVx(IssmDouble* pmaxabsvx){_error_("not implemented yet");};
+		void       MaxAbsVy(IssmDouble* pmaxabsvy){_error_("not implemented yet");};
+		void       MaxAbsVz(IssmDouble* pmaxabsvz){_error_("not implemented yet");};
+		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
+		void       MaxVel(IssmDouble* pmaxvel){_error_("not implemented yet");};
+		void       MaxVx(IssmDouble* pmaxvx){_error_("not implemented yet");};
+		void       MaxVy(IssmDouble* pmaxvy){_error_("not implemented yet");};
+		void       MaxVz(IssmDouble* pmaxvz){_error_("not implemented yet");};
+#endif
+
+#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
+#endif
+
+#ifdef _HAVE_CONTROL_
+		IssmDouble DragCoefficientAbsGradient(void){_error_("not implemented yet");};
+		void       GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
+		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){_error_("not implemented yet");};
+		void       GradjBGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDragGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
+		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
+		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
+		void       ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void       ControlInputScaleGradient(int enum_type,IssmDouble scale){_error_("not implemented yet");};
+		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
+		IssmDouble RheologyBbarAbsGradient(void){_error_("not implemented yet");};
+		IssmDouble ThicknessAbsMisfit(void){_error_("not implemented yet");};
+		IssmDouble SurfaceAbsVelMisfit(void){_error_("not implemented yet");};
+		IssmDouble ThicknessAbsGradient(void){_error_("not implemented yet");};
+		IssmDouble ThicknessAlongGradient(void){_error_("not implemented yet");};
+		IssmDouble ThicknessAcrossGradient(void){_error_("not implemented yet");};
+		IssmDouble BalancethicknessMisfit(void){_error_("not implemented yet");};
+		IssmDouble SurfaceRelVelMisfit(void){_error_("not implemented yet");};
+		IssmDouble SurfaceLogVelMisfit(void){_error_("not implemented yet");};
+		IssmDouble SurfaceLogVxVyMisfit(void){_error_("not implemented yet");};
+		IssmDouble SurfaceAverageVelMisfit(void){_error_("not implemented yet");};
+		void       InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+#endif
+
+#ifdef _HAVE_GROUNDINGLINE_
+		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding){_error_("not implemented yet");};
+		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+#endif
+		/*}}}*/
+		/*Seg specific routines:*/
+		ElementMatrix* CreateMassMatrix(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceTop(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceBase(void);
+		ElementVector* CreatePVectorFreeSurfaceTop(void);
+		ElementVector* CreatePVectorFreeSurfaceBase(void);
+		IssmDouble     GetSize(void);
+};
+#endif  /* _SEG_H */
Index: /issm/trunk/src/c/classes/Elements/SegRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 16560)
+++ /issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 16560)
@@ -0,0 +1,279 @@
+/*!\file SegRef.c
+ * \brief: implementation of the SegRef object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP1  2
+
+/*Object constructors and destructor*/
+/*FUNCTION SegRef::SegRef(){{{*/
+SegRef::SegRef(){
+	this->element_type_list=NULL;
+}
+/*}}}*/
+/*FUNCTION SegRef::SegRef(int* types,int nummodels){{{*/
+SegRef::SegRef(const int nummodels){
+
+	/*Only allocate pointer*/
+	element_type_list=xNew<int>(nummodels);
+
+}
+/*}}}*/
+/*FUNCTION SegRef::~SegRef(){{{*/
+SegRef::~SegRef(){
+	xDelete<int>(element_type_list);
+}
+/*}}}*/
+
+/*Management*/
+/*FUNCTION SegRef::SetElementType{{{*/
+void SegRef::SetElementType(int type,int type_counter){
+
+	/*initialize element type*/
+	this->element_type_list[type_counter]=type;
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+/*FUNCTION SegRef::GetBprimeMasstransport{{{*/
+void SegRef::GetBprimeMasstransport(IssmDouble* Bprime, IssmDouble* xyz_list, GaussSeg* gauss){
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[i] = dbasis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss){{{*/
+void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	GetNodalFunctions(basis,gauss,this->element_type);
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement){{{*/
+void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	switch(element_type){
+		case P1Enum: case P1DGEnum:
+			basis[0]=(1.-gauss->coord1)/2.;
+			basis[1]=(1.+gauss->coord1)/2.;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss){{{*/
+void SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss){
+
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){{{*/
+void SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv, xyz_list, gauss);
+
+	/*Build dbasis: 
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 */
+	for(int i=0;i<numnodes;i++){
+		dbasis[i] = Jinv*dbasis_ref[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss){{{*/
+void SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement){{{*/
+void SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss);
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			/*Nodal function 1*/
+			dbasis[0] = -0.5;
+			/*Nodal function 2*/
+			dbasis[1] = 0.5;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetInputDerivativeValue{{{*/
+void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss){
+
+	/*From node values of parameter p (plist[0],plist[1]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx
+	 *
+	 * p is a vector already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx = 0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(1*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	*p=dpx;
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss){{{*/
+void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss){
+
+	GetInputValue(p,plist,gauss,this->element_type);
+}
+/*}}}*/
+/*FUNCTION SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){{{*/
+void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*p = value;
+}
+/*}}}*/
+/*FUNCTION SegRef::GetJacobian{{{*/
+void SegRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss){
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size 1*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+
+	*J=.5*sqrt(pow(x2-x1,2) + pow(y2-y1,2) + pow(z2-z1,2));
+}
+/*}}}*/
+/*FUNCTION SegRef::GetJacobianDeterminant{{{*/
+void SegRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(Jdet, xyz_list, gauss);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION SegRef::GetJacobianInvert {{{*/
+void SegRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss){
+
+	/*Jacobian*/
+	IssmDouble J;
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J, xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	*Jinv = 1./J;
+}
+/*}}}*/
+/*FUNCTION SegRef::NumberofNodes(){{{*/
+int SegRef::NumberofNodes(void){
+
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+/*FUNCTION SegRef::NumberofNodes(int finiteelement){{{*/
+int SegRef::NumberofNodes(int finiteelement){
+
+	switch(finiteelement){
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/SegRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/SegRef.h	(revision 16560)
+++ /issm/trunk/src/c/classes/Elements/SegRef.h	(revision 16560)
@@ -0,0 +1,41 @@
+
+/*!\file:  SegRef.h
+ * \brief abstract class for handling Seg oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _SEGREF_H_
+#define _SEGREF_H_
+
+class GaussSeg;
+
+class SegRef{
+
+	public: 
+		int* element_type_list;
+		int  element_type;
+
+		SegRef();
+		SegRef(const int nummodels);
+		~SegRef();
+
+		/*Management*/
+		void SetElementType(int type,int type_counter);
+		void GetBprimeMasstransport(IssmDouble* Bprime, IssmDouble* xyz_list, GaussSeg* gauss);
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss);
+		void GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement);
+
+		int  NumberofNodes(void);
+		int  NumberofNodes(int finiteelement);
+};
+#endif
Index: /issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 16560)
@@ -20,18 +20,16 @@
 
 /*Element macros*/
-#define NUMVERTICES 3
+#define NUMVERTICES   3
+#define NUMVERTICES1D 2
+
 /*Constructors/destructor/copy*/
 /*FUNCTION Tria::Tria(){{{*/
 Tria::Tria(){
-
-	int i;
-
-	this->nodes    = NULL;
-	this->vertices = NULL;
-	this->material = NULL;
-	this->matpar   = NULL;
+	this->nodes      = NULL;
+	this->vertices   = NULL;
+	this->material   = NULL;
+	this->matpar     = NULL;
 	this->inputs     = NULL;
 	this->parameters = NULL;
-	this->results    = NULL;
 
 }
@@ -39,17 +37,15 @@
 /*FUNCTION Tria::Tria(int id, int sid,int index, IoModel* iomodel,int nummodels){{{*/
 Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)
-	:TriaRef(nummodels)
-	,ElementHook(nummodels,index+1,3,iomodel){
+	:TriaRef(nummodels),ElementHook(nummodels,index+1,3,iomodel){
 
 		/*id: */
-		this->id=tria_id;
-		this->sid=tria_sid;
+		this->id  = tria_id;
+		this->sid = tria_sid;
 
 		//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
-		this->parameters=NULL;
-
-		/*intialize inputs and results: */
+		this->parameters = NULL;
+
+		/*intialize inputs: */
 		this->inputs  = new Inputs();
-		this->results = new Results();
 
 		/*initialize pointers:*/
@@ -64,5 +60,4 @@
 Tria::~Tria(){
 	delete inputs;
-	delete results;
 	this->parameters=NULL;
 }
@@ -84,11 +79,11 @@
 	tria->hnodes=new Hook*[tria->numanalyses];
 	for(i=0;i<tria->numanalyses;i++)tria->hnodes[i]=(Hook*)this->hnodes[i]->copy();
-	tria->hvertices=(Hook*)this->hvertices->copy();
-	tria->hmaterial=(Hook*)this->hmaterial->copy();
-	tria->hmatpar=(Hook*)this->hmatpar->copy();
+	tria->hvertices = (Hook*)this->hvertices->copy();
+	tria->hmaterial = (Hook*)this->hmaterial->copy();
+	tria->hmatpar   = (Hook*)this->hmatpar->copy();
 
 	/*deal with Tria fields: */
-	tria->id=this->id;
-	tria->sid=this->sid;
+	tria->id  = this->id;
+	tria->sid = this->sid;
 	if(this->inputs){
 		tria->inputs=(Inputs*)this->inputs->Copy();
@@ -97,19 +92,14 @@
 		tria->inputs=new Inputs();
 	}
-	if(this->results){
-		tria->results=(Results*)this->results->Copy();
-	}
-	else{
-		tria->results=new Results();
-	}
 	/*point parameters: */
 	tria->parameters=this->parameters;
 
 	/*recover objects: */
-	tria->nodes=xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	tria->nodes = xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
 	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
-	tria->vertices=(Vertex**)tria->hvertices->deliverp();
-	tria->material=(Material*)tria->hmaterial->delivers();
-	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	tria->vertices = (Vertex**)tria->hvertices->deliverp();
+	tria->material = (Material*)tria->hmaterial->delivers();
+	tria->matpar   = (Matpar*)tria->hmatpar->delivers();
 
 	return tria;
@@ -179,4 +169,5 @@
 void  Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
 
+
 	/*Skip if water element*/
 	if(NoIceInElement()) return;
@@ -208,4 +199,5 @@
 	/*retreive parameters: */
 	int analysis_type;
+	int meshtype;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
@@ -221,16 +213,66 @@
 		#ifdef _HAVE_STRESSBALANCE_
 		case StressbalanceAnalysisEnum:
-			return CreateKMatrixStressbalanceSSA();
+			int approximation;
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case SSAApproximationEnum:
+					return CreateKMatrixStressbalanceSSA();
+				case FSApproximationEnum:
+					return CreateKMatrixStressbalanceFS();
+				case SIAApproximationEnum:
+					return NULL;
+				case NoneApproximationEnum:
+					return NULL;
+				default:
+					_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
 			break;
 		case StressbalanceSIAAnalysisEnum:
 			return CreateKMatrixStressbalanceSIA();
 			break;
-		 #endif
-		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			return CreateMassMatrix();
+		#endif
+	 	#ifdef _HAVE_DAMAGE_
+		case DamageEvolutionAnalysisEnum:
+			return CreateKMatrixDamageEvolution();
 			break;
+		#endif
+		case L2ProjectionBaseAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			if(meshtype==Mesh2DverticalEnum){
+				return CreateBasalMassMatrix();
+			}
+			else{
+				return CreateMassMatrix();
+			}
+			break;
+		#ifdef _HAVE_MASSTRANSPORT_
 		case MasstransportAnalysisEnum:
 			return CreateKMatrixMasstransport();
 			break;
+		case FreeSurfaceTopAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			switch(meshtype){
+				case Mesh2DverticalEnum:
+					return CreateKMatrixFreeSurfaceTop1D();
+				case Mesh3DEnum:
+					return CreateKMatrixFreeSurfaceTop();
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			switch(meshtype){
+				case Mesh2DverticalEnum:
+					return CreateKMatrixFreeSurfaceBase1D();
+				case Mesh3DEnum:
+					return CreateKMatrixFreeSurfaceBase();
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		case ExtrudeFromBaseAnalysisEnum: case ExtrudeFromTopAnalysisEnum:
+			return CreateKMatrixExtrusion();
+		#endif
 		#ifdef _HAVE_HYDROLOGY_
 		case HydrologyShreveAnalysisEnum:
@@ -310,4 +352,20 @@
 }
 /*}}}*/
+/*FUNCTION Tria::CreateBasalMassMatrix{{{*/
+ElementMatrix* Tria::CreateBasalMassMatrix(void){
+
+	if(!HasEdgeOnBed()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnBedIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementMatrix* Ke=seg->CreateMassMatrix();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
 /*FUNCTION Tria::CreateDVector {{{*/
 void  Tria::CreateDVector(Vector<IssmDouble>* df){
@@ -353,5 +411,5 @@
 
 	/*retrive parameters: */
-	ElementVector* pe=NULL;
+	int meshtype;
 	int analysis_type;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -367,19 +425,70 @@
 	/*Just branch to the correct load generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-#ifdef _HAVE_STRESSBALANCE_
+		#ifdef _HAVE_STRESSBALANCE_
 		case StressbalanceAnalysisEnum:
-			return CreatePVectorStressbalanceSSA();
+			int approximation;
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case SSAApproximationEnum:
+					return CreatePVectorStressbalanceSSA();
+				case FSApproximationEnum:
+					return CreatePVectorStressbalanceFS();
+				case SIAApproximationEnum:
+					return NULL;
+				case NoneApproximationEnum:
+					return NULL;
+				default:
+					_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
 			break;
 		case StressbalanceSIAAnalysisEnum:
 			return CreatePVectorStressbalanceSIA();
 			break;
-#endif
-		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			return CreatePVectorSlope();
+		#endif
+	 	#ifdef _HAVE_DAMAGE_
+		case DamageEvolutionAnalysisEnum:
+			return CreatePVectorDamageEvolution();
 			break;
+		#endif
+		case L2ProjectionBaseAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			if(meshtype==Mesh2DverticalEnum){
+				return CreatePVectorL2ProjectionBase();
+			}
+			else{
+				return CreatePVectorL2Projection();
+			}
+			break;
+	 	#ifdef _HAVE_MASSTRANSPORT_
 		case MasstransportAnalysisEnum:
 			return CreatePVectorMasstransport();
 			break;
-#ifdef _HAVE_HYDROLOGY_
+		case FreeSurfaceTopAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			switch(meshtype){
+				case Mesh2DverticalEnum:
+					return CreatePVectorFreeSurfaceTop1D();
+				case Mesh3DEnum:
+					return CreatePVectorFreeSurfaceTop();
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			parameters->FindParam(&meshtype,MeshTypeEnum);
+			switch(meshtype){
+				case Mesh2DverticalEnum:
+					return CreatePVectorFreeSurfaceBase1D();
+				case Mesh3DEnum:
+					return CreatePVectorFreeSurfaceBase();
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		case ExtrudeFromBaseAnalysisEnum: case ExtrudeFromTopAnalysisEnum:
+			return NULL;
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
 		case HydrologyShreveAnalysisEnum:
 			return CreatePVectorHydrologyShreve();
@@ -391,6 +500,6 @@
 			return CreatePVectorHydrologyDCEfficient();
 			break;
-#endif
-#ifdef _HAVE_BALANCED_
+		#endif
+		#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
 			return CreatePVectorBalancethickness();
@@ -405,6 +514,6 @@
 			return CreatePVectorSmoothedSlopeY();
 			break;
-#endif
-#ifdef _HAVE_CONTROL_
+		#endif
+		#ifdef _HAVE_CONTROL_
 		case AdjointBalancethicknessAnalysisEnum:
 			return CreatePVectorAdjointBalancethickness();
@@ -413,5 +522,5 @@
 			return CreatePVectorAdjointHoriz();
 			break;
-#endif
+	 	#endif
 		default:
 			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
@@ -422,12 +531,30 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVectorSlope {{{*/
-ElementVector* Tria::CreatePVectorSlope(void){
+/*FUNCTION Tria::CreatePVectorL2ProjectionBase{{{*/
+ElementVector* Tria::CreatePVectorL2ProjectionBase(void){
+
+	if(!HasEdgeOnBed()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnBedIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementVector* pe=seg->CreatePVectorL2Projection();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorL2Projection {{{*/
+ElementVector* Tria::CreatePVectorL2Projection(void){
 
 	/*Intermediaries */
-	int        i,analysis_type;
-	IssmDouble Jdet;
+	int        i,input_enum;
+	IssmDouble Jdet,value;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble slope[2];
+	IssmDouble slopes[2];
+	Input*     input  = NULL;
+	Input*     input2 = NULL;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -439,12 +566,12 @@
 
 	/*Retrieve all inputs and parameters*/
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,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);
+	this->parameters->FindParam(&input_enum,InputToL2ProjectEnum);
+	switch(input_enum){
+		case SurfaceSlopeXEnum: input2 = inputs->GetInput(SurfaceEnum); _assert_(input2); break;
+		case SurfaceSlopeYEnum: input2 = inputs->GetInput(SurfaceEnum); _assert_(input2); break;
+		case BedSlopeXEnum:     input2 = inputs->GetInput(BedEnum);     _assert_(input2); break;
+		case BedSlopeYEnum:     input2 = inputs->GetInput(BedEnum);     _assert_(input2); break;
+		default: input = inputs->GetInput(input_enum);
 	}
 
@@ -458,12 +585,12 @@
 		GetNodalFunctions(basis,gauss);
 
-		slope_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
-
-		if( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==BedSlopeXAnalysisEnum)){
-			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*slope[0]*basis[i];
-		}
-		if( (analysis_type==SurfaceSlopeYAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
-			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*slope[1]*basis[i];
-		}
+		if(input2) input2->GetInputDerivativeValue(&slopes[0],&xyz_list[0][0],gauss);
+		switch(input_enum){
+			case SurfaceSlopeXEnum: case BedSlopeXEnum: value = slopes[0]; break;
+			case SurfaceSlopeYEnum: case BedSlopeYEnum: value = slopes[1]; break;
+			default: input->GetInputValue(&value,gauss);
+		}
+
+		for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*value*basis[i];
 	}
 
@@ -625,17 +752,5 @@
 	else _printf_("inputs=NULL\n");
 
-	if (results) results->DeepEcho();
-	else _printf_("results=NULL\n");
-
 	return;
-}
-/*}}}*/
-/*FUNCTION Tria::DeleteResults {{{*/
-void  Tria::DeleteResults(void){
-
-	/*Delete and reinitialize results*/
-	delete this->results;
-	this->results=new Results();
-
 }
 /*}}}*/
@@ -701,4 +816,6 @@
 		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
 	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
 
 	this->inputs->AddInput(NewTemperatureInput);
@@ -733,7 +850,4 @@
 	if (inputs) inputs->Echo();
 	else _printf_("inputs=NULL\n");
-
-	if (results) results->Echo();
-	else _printf_("results=NULL\n");
 }
 /*}}}*/
@@ -748,5 +862,4 @@
 IssmDouble Tria::GetArea(void){
 
-	IssmDouble area=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble x1,y1,x2,y2,x3,y3;
@@ -822,4 +935,53 @@
 }
 /*}}}*/
+/*FUNCTION Tria::GetDofListVelocity{{{*/
+void  Tria::GetDofListVelocity(int** pdoflist,int setenum){
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodesVelocity();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=0;i<numnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSvelocityEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Tria::GetDofListPressure{{{*/
+void  Tria::GetDofListPressure(int** pdoflist,int setenum){
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSApproximationEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
 /*FUNCTION Tria::GetElementType {{{*/
 int Tria::GetElementType(){
@@ -1006,5 +1168,5 @@
 	/*Computeportion of the element that is grounded*/ 
 
-	int         normal_orientation;
+	int         normal_orientation=0;
 	IssmDouble  s1,s2;
 	IssmDouble  levelset[NUMVERTICES];
@@ -1013,10 +1175,10 @@
 	GetInputListOnVertices(&levelset[0],levelsetenum);
 
-	if(levelset[0]*levelset[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
 		/*Portion of the segments*/
 		s1=levelset[2]/(levelset[2]-levelset[1]);
 		s2=levelset[2]/(levelset[2]-levelset[0]);
 
-		if(levelset[2]>0) normal_orientation=1;
+		if(levelset[2]>0.) normal_orientation=1;
 		/*New point 1*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[2][0]+s1*(xyz_list[1][0]-xyz_list[2][0]);
@@ -1029,10 +1191,10 @@
 		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2][2]+s2*(xyz_list[0][2]-xyz_list[2][2]);
 	}
-	else if(levelset[1]*levelset[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
 		/*Portion of the segments*/
 		s1=levelset[0]/(levelset[0]-levelset[2]);
 		s2=levelset[0]/(levelset[0]-levelset[1]);
 
-		if(levelset[0]>0) normal_orientation=1;
+		if(levelset[0]>0.) normal_orientation=1;
 		/*New point 1*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[0][0]+s1*(xyz_list[2][0]-xyz_list[0][0]);
@@ -1045,10 +1207,10 @@
 		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0][2]+s2*(xyz_list[1][2]-xyz_list[0][2]);
 	}
-	else if(levelset[0]*levelset[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
 		/*Portion of the segments*/
 		s1=levelset[1]/(levelset[1]-levelset[0]);
 		s2=levelset[1]/(levelset[1]-levelset[2]);
 
-		if(levelset[1]>0) normal_orientation=1;
+		if(levelset[1]>0.) normal_orientation=1;
 		/*New point 0*/
 		xyz_zero[3*normal_orientation+0]=xyz_list[1][0]+s1*(xyz_list[0][0]-xyz_list[1][0]);
@@ -1061,5 +1223,5 @@
 		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1][2]+s2*(xyz_list[2][2]-xyz_list[1][2]);
 	}
-	else if(levelset[0]==0 && levelset[1]==0){ //front is on point 0 and 1
+	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[0][0];
 		xyz_zero[3*0+1]=xyz_list[0][1];
@@ -1071,5 +1233,5 @@
 		xyz_zero[3*1+2]=xyz_list[1][2];
 	}
-	else if(levelset[0]==0 && levelset[2]==0){ //front is on point 0 and 1
+	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[2][0];
 		xyz_zero[3*0+1]=xyz_list[2][1];
@@ -1081,5 +1243,5 @@
 		xyz_zero[3*1+2]=xyz_list[0][2];
 	}
-	else if(levelset[1]==0 && levelset[2]==0){ //front is on point 0 and 1
+	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
 		xyz_zero[3*0+0]=xyz_list[1][0];
 		xyz_zero[3*0+1]=xyz_list[1][1];
@@ -1228,6 +1390,5 @@
 	/*Recover input*/
 	Input* input=inputs->GetInput(enumtype);
-	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
-	int    numnodes = this->NumberofNodes();
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
 
 	/* Start looping on the number of vertices: */
@@ -1253,4 +1414,17 @@
 }
 /*}}}*/
+/*FUNCTION Tria::GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype) {{{*/
+void Tria::GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype){
+
+	Input* input=this->material->inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
 /*FUNCTION Tria::GetVertexPidList {{{*/
 void  Tria::GetVertexPidList(int* doflist){
@@ -1281,5 +1455,15 @@
 	#ifdef _HAVE_STRESSBALANCE_
 	case StressbalanceAnalysisEnum:
-		GetSolutionFromInputsStressbalanceHoriz(solution);
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+			GetSolutionFromInputsStressbalanceFS(solution);
+		}
+		else if (approximation==SSAApproximationEnum || approximation==SIAApproximationEnum){
+			GetSolutionFromInputsStressbalanceHoriz(solution);
+		}
+		else{
+			_error_("approximation not supported yet");
+		}
 		break;
 	case StressbalanceSIAAnalysisEnum:
@@ -1345,27 +1529,4 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GetVectorFromResults{{{*/
-void  Tria::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
-
-	/*Get result*/
-	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
-	if(elementresult->InstanceEnum()!=enum_in){
-		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
-	}
-	if(interp==P1Enum){
-		int vertexpidlist[NUMVERTICES];
-		int connectivity[NUMVERTICES];
-		this->GetVertexSidList(&vertexpidlist[0]);
-		this->GetConnectivityList(&connectivity[0]);
-		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
-	}
-	else if(interp==P0Enum){
-		elementresult->GetElementVectorFromResults(vector,sid);
-	}
-	else{
-		_printf_("Interpolation " << EnumToStringx(interp) << " not supported\n");
-	}
-}
-/*}}}*/
 /*FUNCTION Tria::Id {{{*/
 int    Tria::Id(){
@@ -1380,17 +1541,4 @@
 	return sid;
 
-}
-/*}}}*/
-/*FUNCTION Tria::InputArtificialNoise{{{*/
-void  Tria::InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max){
-
-	Input* input=NULL;
-
-	/*Make a copy of the original input: */
-	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
-
-	/*ArtificialNoise: */
-	input->ArtificialNoise(min,max);
 }
 /*}}}*/
@@ -1445,32 +1593,9 @@
 }
 /*}}}*/
-/*FUNCTION Tria::InputToResult{{{*/
-void  Tria::InputToResult(int enum_type,int step,IssmDouble time){
-
-	Input *input = NULL;	
-
-	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
-	if (enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum)
-	 input=this->material->inputs->GetInput(enum_type);
-	else
-	 input=this->inputs->GetInput(enum_type);
-	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
-	if(!input)return;
-
-	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
-	 * object out of the input, with the additional step and time information: */
-	this->results->AddResult(input->SpawnResult(step,time));
-
-	#ifdef _HAVE_CONTROL_
-	if(input->ObjectEnum()==ControlInputEnum){
-		if(((ControlInput*)input)->gradient!=NULL) this->results->AddResult(((ControlInput*)input)->SpawnGradient(step,time));
-	}
-	#endif
-}
-/*}}}*/
 /*FUNCTION Tria::InputUpdateFromConstant(int value, int name);{{{*/
 void  Tria::InputUpdateFromConstant(int constant, int name){
+
 	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
+	if(!IsInput(name)) return;
 
 	/*update input*/
@@ -1480,6 +1605,7 @@
 /*FUNCTION Tria::InputUpdateFromConstant(IssmDouble value, int name);{{{*/
 void  Tria::InputUpdateFromConstant(IssmDouble constant, int name){
+
 	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
+	if(!IsInput(name)) return;
 
 	/*update input*/
@@ -1489,6 +1615,7 @@
 /*FUNCTION Tria::InputUpdateFromConstant(bool value, int name);{{{*/
 void  Tria::InputUpdateFromConstant(bool constant, int name){
+
 	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
+	if(!IsInput(name)) return;
 
 	/*update input*/
@@ -1506,7 +1633,6 @@
 	IssmDouble cmmaxinputs[3];
 	bool       control_analysis   = false;
-	int        num_control_type;
+	int        num_control_type,num_responses;
 	IssmDouble yts;
-	int        num_cm_responses;
 
 	/*Get parameters: */
@@ -1514,5 +1640,5 @@
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
-	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);
 
 	/*Recover vertices ids needed to initialize inputs*/
@@ -1520,4 +1646,10 @@
 		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
 	}
+
+	/*Need to know the type of approximation for this element*/
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
+	}
+
 
 	/*Control Inputs*/
@@ -1566,7 +1698,7 @@
 					}
 					break;
-				case MaterialsRheologyBbarEnum:
-				case MaterialsRheologyZbarEnum:
-					/*Material will take care of it*/ break;
+				/*Material will take care of it*/ 
+				case MaterialsRheologyBbarEnum:break;
+				case DamageDbarEnum: break;
 				default:
 					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
@@ -1581,7 +1713,7 @@
 		/*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 TriaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum));
+		for(i=0;i<num_responses;i++){
+			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_responses+i];
+			datasetinput->AddInput(new TriaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
 		}
 
@@ -1595,5 +1727,5 @@
 
 	/*retrive parameters: */
-	int analysis_type;
+	int analysis_type,extrusioninput;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
@@ -1602,5 +1734,15 @@
 		#ifdef _HAVE_STRESSBALANCE_
 		case StressbalanceAnalysisEnum:
-			InputUpdateFromSolutionStressbalanceHoriz(solution);
+			int approximation;
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+				InputUpdateFromSolutionStressbalanceFS(solution);
+			}
+			else if (approximation==SSAApproximationEnum || approximation==SIAApproximationEnum){
+				InputUpdateFromSolutionStressbalanceHoriz(solution);
+			}
+			else{
+				_error_("approximation not supported yet");
+			}
 			break;
 		case StressbalanceSIAAnalysisEnum:
@@ -1627,4 +1769,9 @@
 			break;
 		#endif
+	 	#ifdef _HAVE_DAMAGE_
+		case DamageEvolutionAnalysisEnum:
+			InputUpdateFromSolutionDamageEvolution(solution);
+			break;
+		#endif
 	 	#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
@@ -1641,18 +1788,20 @@
 			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);
+		case L2ProjectionBaseAnalysisEnum:
+			this->parameters->FindParam(&extrusioninput,InputToL2ProjectEnum);
+			InputUpdateFromSolutionOneDof(solution,extrusioninput);
 			break;
 		case MasstransportAnalysisEnum:
 			InputUpdateFromSolutionMasstransport(solution);
+			break;
+		case FreeSurfaceTopAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,BedEnum);
+			break;
+		case ExtrudeFromBaseAnalysisEnum: case ExtrudeFromTopAnalysisEnum:
+			this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+			InputUpdateFromSolutionOneDof(solution,extrusioninput);
 			break;
 		default:
@@ -1767,5 +1916,4 @@
 void  Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type){
 
-
 	/*Check that name is an element input*/
 	if (!IsInput(name)) return;
@@ -1777,9 +1925,10 @@
 	switch(type){
 	case VertexPIdEnum: 
-		for (int i=0;i<NUMVERTICES;i++){
+		values = xNew<IssmDouble>(NUMVERTICES);
+		for(int i=0;i<NUMVERTICES;i++){
 			values[i]=vector[this->vertices[i]->Pid()];
 		}
 		/*update input*/
-		if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+		if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==DamageDEnum || name==DamageDbarEnum){
 			material->inputs->AddInput(new TriaInput(name,values,P1Enum));
 		}
@@ -1787,12 +1936,13 @@
 			this->inputs->AddInput(new TriaInput(name,values,P1Enum));
 		}
-		return; 
+		break;
 
 	case VertexSIdEnum: 
-		for (int i=0;i<NUMVERTICES;i++){
+		values = xNew<IssmDouble>(NUMVERTICES);
+		for(int i=0;i<NUMVERTICES;i++){
 			values[i]=vector[this->vertices[i]->Sid()];
 		}
 		/*update input*/
-		if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+		if(name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==DamageDEnum || name==DamageDbarEnum){
 			material->inputs->AddInput(new TriaInput(name,values,P1Enum));
 		}
@@ -1800,5 +1950,5 @@
 			this->inputs->AddInput(new TriaInput(name,values,P1Enum));
 		}
-		return; 
+		break;
 
 	case NodesEnum:
@@ -1809,16 +1959,10 @@
 		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
 
-		/*Use the dof list to index into the vector: */
 		for(int i=0;i<numnodes;i++){
 			values[i]=vector[doflist[i]];
 			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
 		}
-
-		/*Add input to the element: */
 		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
-
-		/*Free ressources:*/
-		xDelete<int>(doflist);
-		return;
+		break;
 
 	case NodeSIdEnum:
@@ -1832,7 +1976,6 @@
 			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
 		}
-		/*Add input to the element: */
 		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
-		return;
+		break;
 
 	default:
@@ -1846,28 +1989,9 @@
 }
 /*}}}*/
-/*FUNCTION Tria::InputCreate(IssmDouble scalar,int enum,int code);{{{*/
-void Tria::InputCreate(IssmDouble scalar,int name,int code){
-
-	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
-
-	if ((code==5) || (code==1)){ //boolean
-		this->inputs->AddInput(new BoolInput(name,reCast<bool>(scalar)));
-	}
-	else if ((code==6) || (code==2)){ //integer
-		this->inputs->AddInput(new IntInput(name,reCast<int>(scalar)));
-	}
-	else if ((code==7) || (code==3)){ //IssmDouble
-		this->inputs->AddInput(new DoubleInput(name,reCast<int>(scalar)));
-	}
-	else _error_("could not recognize nature of vector from code " << code);
-
-}
-/*}}}*/
-/*FUNCTION Tria::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
-void Tria::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+/*FUNCTION Tria::InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Tria::InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){
 
 	/*Intermediaries*/
-	int    i,j,t;
+	int    i,t;
 	int    tria_vertex_ids[3];
 	int    row;
@@ -1882,5 +2006,5 @@
 		for(i=0;i<3;i++){ 
 			_assert_(iomodel->elements);
-			tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
+			tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*this->sid+i]); //ids for vertices are in the elements array from Matlab
 		}
 
@@ -1889,5 +2013,5 @@
 
 			/*create input values: */
-			for(i=0;i<3;i++)nodeinputs[i]=(IssmDouble)vector[tria_vertex_ids[i]-1];
+			for(i=0;i<3;i++)nodeinputs[i]=vector[tria_vertex_ids[i]-1];
 
 			/*create static input: */
@@ -1901,9 +2025,9 @@
 				for(i=0;i<3;i++){
 					row=tria_vertex_ids[i]-1;
-					nodeinputs[i]=(IssmDouble)vector[N*row+t];
+					nodeinputs[i]=vector[N*row+t];
 				}
 
 				/*time? :*/
-				time=(IssmDouble)vector[(M-1)*N+t];
+				time=vector[(M-1)*N+t];
 
 				if(t==0) transientinput=new TransientInput(vector_enum);
@@ -1921,11 +2045,11 @@
 
 			if (code==5){ //boolean
-				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[index])));
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[this->sid])));
 			}
 			else if (code==6){ //integer
-				this->inputs->AddInput(new IntInput(vector_enum,reCast<int>(vector[index])));
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int>(vector[this->sid])));
 			}
 			else if (code==7){ //IssmDouble
-				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[this->sid]));
 			}
 			else _error_("could not recognize nature of vector from code " << code);
@@ -1958,9 +2082,10 @@
 				name==VxEnum ||
 				name==VyEnum ||
+				name==PressureEnum ||
 				name==InversionVxObsEnum ||
 				name==InversionVyObsEnum ||
 				name==FrictionCoefficientEnum ||
 				name==MaterialsRheologyBbarEnum ||
-				name==MaterialsRheologyZbarEnum ||
+				name==DamageDbarEnum ||
 				name==GradientEnum ||
 				name==OldGradientEnum ||
@@ -1971,4 +2096,5 @@
 				name==EplHeadEnum ||
 				name==HydrologydcMaskEplactiveEnum ||
+				name==MeshVertexonbedEnum ||
 				name==WaterTransferEnum ||
 				name==QmuVxEnum ||
@@ -1980,4 +2106,6 @@
 				name==QmuTemperatureEnum ||
 				name==QmuMeltingEnum || 
+				name==QmuMaskGroundediceLevelsetEnum ||
+				name==QmuMaskIceLevelsetEnum ||
 				name==GiaWEnum || 
 				name==GiadWdtEnum
@@ -1996,4 +2124,128 @@
 }
 /*}}}*/
+/*FUNCTION Tria::HasEdgeOnBed {{{*/
+bool Tria::HasEdgeOnBed(){
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on bed not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::HasEdgeOnSurface {{{*/
+bool Tria::HasEdgeOnSurface(){
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on surface not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::EdgeOnBedIndices{{{*/
+void Tria::EdgeOnBedIndices(int* pindex1,int* pindex2){
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+/*FUNCTION Tria::EdgeOnSurfaceIndices{{{*/
+void Tria::EdgeOnSurfaceIndices(int* pindex1,int* pindex2){
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
+/*FUNCTION Tria::EdgeOnBedIndex{{{*/
+int Tria::EdgeOnBedIndex(void){
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+/*FUNCTION Tria::EdgeOnSurfaceIndex{{{*/
+int Tria::EdgeOnSurfaceIndex(void){
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
 /*FUNCTION Tria::IsFloating {{{*/
 bool   Tria::IsFloating(){
@@ -2045,55 +2297,4 @@
 }
 /*}}}*/
-/*FUNCTION Tria::ListResultsInfo{{{*/
-void Tria::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,IssmDouble** in_resultstimes,int** in_resultssteps,int* in_num_results){
-
-	/*Intermediaries*/
-	int     i;
-	int     numberofresults = 0;
-	int     *resultsenums   = NULL;
-	int     *resultssizes   = NULL;
-	IssmDouble  *resultstimes   = NULL;
-	int     *resultssteps   = NULL;
-
-	/*Checks*/
-	_assert_(in_num_results);
-
-	/*Count number of results*/
-	for(i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-		numberofresults++;
-	}
-
-	if(numberofresults){
-
-		/*Allocate output*/
-		resultsenums=xNew<int>(numberofresults);
-		resultssizes=xNew<int>(numberofresults);
-		resultstimes=xNew<IssmDouble>(numberofresults);
-		resultssteps=xNew<int>(numberofresults);
-
-		/*populate enums*/
-		for(i=0;i<this->results->Size();i++){
-			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-			resultsenums[i]=elementresult->InstanceEnum();
-			resultstimes[i]=elementresult->GetTime();
-			resultssteps[i]=elementresult->GetStep();
-			if(elementresult->ObjectEnum()==TriaP1ElementResultEnum){
-				resultssizes[i]=P1Enum;
-			}
-			else{
-				resultssizes[i]=P0Enum;
-			}
-		}
-	}
-
-	/*Assign output pointers:*/
-	*in_num_results=numberofresults;
-	*in_resultsenums=resultsenums;
-	*in_resultssizes=resultssizes;
-	*in_resultstimes=resultstimes;
-	*in_resultssteps=resultssteps;
-
-}/*}}}*/
 /*FUNCTION Tria::NodalValue {{{*/
 int    Tria::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){
@@ -2127,55 +2328,4 @@
 	if(found)*pvalue=value;
 	return found;
-}
-/*}}}*/
-/*FUNCTION Tria::PatchFill{{{*/
-void  Tria::PatchFill(int* prow, Patch* patch){
-
-	int i,row;
-	int vertices_ids[3];
-
-	/*recover pointer: */
-	row=*prow;
-
-	for(i=0;i<3;i++) vertices_ids[i]=vertices[i]->Id(); //vertices id start at column 3 of the patch.
-
-	for(i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-
-		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
-		 *it to the result object, to fill the rest: */
-		patch->fillelementinfo(row,this->sid+1,vertices_ids,3);
-		elementresult->PatchFill(row,patch);
-
-		/*increment rower: */
-		row++;
-	}
-
-	/*Assign output pointers:*/
-	*prow=row;
-}
-/*}}}*/
-/*FUNCTION Tria::PatchSize{{{*/
-void  Tria::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
-
-	int     i;
-	int     numrows       = 0;
-	int     numnodes      = 0;
-	int     temp_numnodes = 0;
-
-	/*Go through all the results objects, and update the counters: */
-	for (i=0;i<this->results->Size();i++){
-		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
-		/*first, we have one more result: */
-		numrows++;
-		/*now, how many vertices and how many nodal values for this result? :*/
-		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
-		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
-	}
-
-	/*Assign output pointers:*/
-	*pnumrows=numrows;
-	*pnumvertices=NUMVERTICES;
-	*pnumnodes=numnodes;
 }
 /*}}}*/
@@ -2230,29 +2380,115 @@
 }
 /*}}}*/
-/*FUNCTION Tria::RequestedOutput{{{*/
-void Tria::RequestedOutput(int output_enum,int step,IssmDouble time){
-
-	if(IsInput(output_enum)){
-		/*just transfer this input to results, and we are done: */
-		InputToResult(output_enum,step,time);
-	}
-	else{
-		/*this input does not exist, compute it, and then transfer to results: */
+/*FUNCTION Tria::ResetCoordinateSystem{{{*/
+void  Tria::ResetCoordinateSystem(void){
+
+	int        approximation;
+	int        numindices;
+	int       *indices = NULL;
+	IssmDouble slope;
+	IssmDouble xz_plane[6];
+
+	/*For FS only: we want the CS to be tangential to the bedrock*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(IsFloating() || !HasEdgeOnBed() || approximation!=FSApproximationEnum) return;
+
+	/*Get number of nodes for velocity only and base*/
+	int index = this->EdgeOnBedIndex();
+	NodeOnEdgeIndices(&numindices,&indices,index,this->VelocityInterpolation());
+
+	/*Get inputs*/
+	Input* slope_input=inputs->GetInput(BedSlopeXEnum); _assert_(slope_input);
+
+	/*Loop over basal nodes and update their CS*/
+	GaussTria* gauss = new GaussTria();
+	for(int i=0;i<numindices;i++){//FIXME
+
+		gauss->GaussNode(this->VelocityInterpolation(),indices[i]);
+		slope_input->GetInputValue(&slope,gauss);
+		IssmDouble theta = atan(slope);
+
+		/*New X axis                  New Z axis*/
+		xz_plane[0]=cos(theta);       xz_plane[3]=0.;  
+		xz_plane[1]=sin(theta);       xz_plane[4]=0.;  
+		xz_plane[2]=0.;               xz_plane[5]=1.;          
+
+		XZvectorsToCoordinateSystem(&this->nodes[indices[i]]->coord_system[0][0],&xz_plane[0]);
+	}
+
+	/*cleanup*/
+	xDelete<int>(indices);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::ResultInterpolation{{{*/
+void Tria::ResultInterpolation(int* pinterpolation,int output_enum){
+
+	Input* input=this->inputs->GetInput(output_enum);
+
+	/*If this input is not already in Inputs, maybe it needs to be computed?*/
+	if(!input){
 		switch(output_enum){
-			case StressTensorEnum: 
+			case StressTensorxxEnum: 
 				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);
+				input=this->inputs->GetInput(output_enum);
 				break;
-
+			case StressTensorxyEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensorxzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensoryyEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensoryzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensorzzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
 			default:
-				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
-				break;
-		}
-	}
+				_error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+		}
+	}
+
+	/*Assign output pointer*/
+	*pinterpolation = input->GetResultInterpolation();
+
+}
+/*}}}*/
+/*FUNCTION Tria::ResultToVector{{{*/
+void Tria::ResultToVector(Vector<IssmPDouble>* vector,int output_enum){
+
+	Input* input=this->inputs->GetInput(output_enum);
+	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+
+	switch(input->GetResultInterpolation()){
+		case P0Enum:
+			_error_("not implemented...");
+			break;
+		case P1Enum:{
+			IssmDouble  values[NUMVERTICES];
+			IssmPDouble pvalues[NUMVERTICES]; 
+			int         connectivity[NUMVERTICES];
+			int         sidlist[NUMVERTICES];
+
+			this->GetVertexSidList(&sidlist[0]);
+			this->GetConnectivityList(&connectivity[0]);
+			this->GetInputListOnVertices(&values[0],output_enum);
+			for(int i=0;i<NUMVERTICES;i++) pvalues[i] = reCast<IssmPDouble>(values[i])/reCast<IssmPDouble>(connectivity[i]);
+
+			vector->SetValues(NUMVERTICES,&sidlist[0],&pvalues[0],ADD_VAL);
+			break;
+					}
+		default:
+			_error_("interpolation "<<EnumToStringx(input->GetResultInterpolation())<<" not supported yet");
+	}
+
 
 }
@@ -2326,4 +2562,34 @@
 }
 /*}}}*/
+/*FUNCTION Tria::SpawnSeg {{{*/
+Seg*  Tria::SpawnSeg(int index1,int index2){
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Create Seg*/
+	Seg* seg=new Seg();
+	seg->id=this->id;
+	seg->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	seg->parameters=this->parameters;
+	seg->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnSegHook(dynamic_cast<ElementHook*>(seg),index1,index2);
+
+	/*Spawn material*/
+	seg->material=(Material*)this->material->copy();
+	delete seg->material->inputs;
+	seg->material->inputs=(Inputs*)this->material->inputs->SpawnSegInputs(index1,index2);
+
+	/*recover nodes, material and matpar: */
+	seg->nodes    = (Node**)seg->hnodes[analysis_counter]->deliverp();
+	seg->vertices = (Vertex**)seg->hvertices->deliverp();
+	seg->matpar   = (Matpar*)seg->hmatpar->delivers();
+
+	/*Return new Seg*/
+	return seg;
+}
+/*}}}*/
 /*FUNCTION Tria::SurfaceArea {{{*/
 IssmDouble Tria::SurfaceArea(void){
@@ -2427,33 +2693,12 @@
 
 	/*Intermediaries*/
-	int        i,j;
-	int        tria_vertex_ids[3];
-	IssmDouble nodeinputs[3];
-	IssmDouble yts;
-	int        progstabilization,balancestabilization;
-	int        fe_ssa;
-	bool       dakota_analysis;
-	int        numnodes;
-	int*       tria_node_ids = NULL;
+	int  numnodes;
+	int* tria_node_ids = NULL;
 
 	/*Checks if debuging*/
-	/*{{{*/
 	_assert_(iomodel->elements);
-	/*}}}*/
-
-	/*Fetch parameters: */
-	iomodel->Constant(&yts,ConstantsYtsEnum);
-	iomodel->Constant(&progstabilization,MasstransportStabilizationEnum);
-	iomodel->Constant(&balancestabilization,BalancethicknessStabilizationEnum);
-	iomodel->Constant(&fe_ssa,FlowequationFeSSAEnum);
-	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
 
 	/*Recover element type*/
 	this->SetElementType(finiteelement_type,analysis_counter);
-
-	/*Recover vertices ids needed to initialize inputs*/
-	for(i=0;i<3;i++){ 
-		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
-	}
 
 	/*Recover nodes ids needed to initialize the node hook.*/
@@ -2491,4 +2736,41 @@
 			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
 			break;
+		case P1P1Enum: case P1P1GLSEnum:
+			numnodes        = 6;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+0];
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+1];
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+2];
+			break;
+		case MINIEnum: case MINIcondensedEnum:
+			numnodes       = 7;
+			tria_node_ids  = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+0];
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+1];
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+2];
+			break;
+		case TaylorHoodEnum:
+			numnodes        = 9;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+0];
+			tria_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+1];
+			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+2];
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -2501,43 +2783,48 @@
 	/*Fill with IoModel*/
 	this->InputUpdateFromIoModel(index,iomodel);
-
-	/*Defaults if not provided in iomodel*/
-	switch(analysis_type){
-
-		case StressbalanceAnalysisEnum:
-
-			/*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 TriaInput(VxEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVxEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(VyEnum)){
-				for(i=0;i<3;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new TriaInput(VyEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVyEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(VzEnum)){
-				for(i=0;i<3;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new TriaInput(VzEnum,nodeinputs,P1Enum));
-				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVzEnum,nodeinputs,P1Enum));
-			}
-			if(!iomodel->Data(PressureEnum)){
-				for(i=0;i<3;i++)nodeinputs[i]=0;
-				if(dakota_analysis){
-					this->inputs->AddInput(new TriaInput(PressureEnum,nodeinputs,P1Enum));
-					this->inputs->AddInput(new TriaInput(QmuPressureEnum,nodeinputs,P1Enum));
-				}
-			}
-			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::UpdateConstraintsExtrudeFromBase{{{*/
+void  Tria::UpdateConstraintsExtrudeFromBase(void){
+
+	if(!HasEdgeOnBed()) return;
+
+	int extrusioninput;
+	int indices[2];
+	IssmDouble value;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput); _assert_(extrusioninput);
+	this->EdgeOnBedIndices(&indices[0],&indices[1]);
+
+	GaussTria* gauss=new GaussTria();
+	for(int i=0;i<2;i++){
+		gauss->GaussNode(P1Enum,indices[i]);
+		input->GetInputValue(&value,gauss);
+		this->nodes[indices[i]]->ApplyConstraint(1,value);
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::UpdateConstraintsExtrudeFromTop{{{*/
+void  Tria::UpdateConstraintsExtrudeFromTop(void){
+
+	if(!HasEdgeOnSurface()) return;
+
+	int extrusioninput;
+	int indices[2];
+	IssmDouble value;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput); _assert_(extrusioninput);
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+
+	GaussTria* gauss=new GaussTria();
+	for(int i=0;i<2;i++){
+		gauss->GaussNode(P1Enum,indices[i]);
+		input->GetInputValue(&value,gauss);
+		this->nodes[indices[i]]->ApplyConstraint(1,value);
+	}
+
 }
 /*}}}*/
@@ -2609,8 +2896,103 @@
 }
 /*}}}*/
+/*FUNCTION Tria::IceVolumeAboveFloatation {{{*/
+IssmDouble Tria::IceVolumeAboveFloatation(void){
+
+	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,surface,bed,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(NoIceInElement() || IsFloating())return 0;
+
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height and bathymetry*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* bed_input        = inputs->GetInput(BedEnum);        _assert_(bed_input);
+	Input* bathymetry_input = inputs->GetInput(BathymetryEnum); _assert_(bathymetry_input);
+	surface_input->GetInputAverage(&surface);
+	bed_input->GetInputAverage(&bed);
+	bathymetry_input->GetInputAverage(&bathymetry);
+	
+	/*Return: */
+	return base*(surface-bed+min(rho_water/rho_ice*bathymetry,0.));
+}
+/*}}}*/
+/*FUNCTION Tria::MassFlux {{{*/
+IssmDouble Tria::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){
+
+	int        meshtype;
+	IssmDouble mass_flux=0.;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	/*First off, check that this segment belongs to this element: */
+	if (segment_id!=this->id)_error_("error message: segment with id " << segment_id << " does not belong to element with id:" << this->id);
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(meshtype==Mesh2DhorizontalEnum){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
 /*FUNCTION Tria::MassFlux {{{*/
 IssmDouble Tria::MassFlux( IssmDouble* segment){
 
-	int        dim;
+	int        meshtype;
 	IssmDouble mass_flux=0.;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -2646,8 +3028,8 @@
 
 	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
 	Input* vx_input=NULL;
 	Input* vy_input=NULL;
-	if(dim==2){
+	if(meshtype==Mesh2DhorizontalEnum){
 		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
@@ -2794,7 +3176,5 @@
 			*presponse=this->material->GetBbar();
 			break;
-		case MaterialsRheologyZbarEnum:
-			*presponse=this->material->GetZbar();
-			break;
+
 		case VelEnum:{
 
@@ -2976,4 +3356,162 @@
 
 #ifdef _HAVE_STRESSBALANCE_
+/*FUNCTION Tria::CreateKMatrixStressbalanceFS{{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceFS(void){
+
+	ElementMatrix* Ke1 = NULL;
+	ElementMatrix* Ke2 = NULL;
+	ElementMatrix* Ke  = NULL;
+
+	/*compute all stiffness matrices for this element*/
+	Ke1=CreateKMatrixStressbalanceFSViscous();
+	Ke2=CreateKMatrixStressbalanceFSFriction();
+	Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixStressbalanceFSViscous {{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceFSViscous(void){
+
+	/*Intermediaries */
+	int        i,approximation;
+	IssmDouble Jdet,viscosity,FSreconditioning,D_scalar;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	GaussTria *gauss=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numdof    = vnumnodes*NDOF2 + pnumnodes*NDOF1;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(5*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(5*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(5*5);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBFS(B,&xyz_list[0][0],gauss); 
+		GetBprimeFS(Bprime,&xyz_list[0][0],gauss); 
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosity2dvertical(&viscosity,&epsilon[0]);
+
+		D_scalar=gauss->weight*Jdet;
+		for(i=0;i<3;i++) D[i*5+i] = +D_scalar*2.*viscosity;
+		for(i=3;i<5;i++) D[i*5+i] = -D_scalar*FSreconditioning;
+
+		TripleMultiply(B,5,numdof,1,
+					D,5,5,0,
+					Bprime,5,numdof,0,
+					Ke->values,1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,(vnumnodes+pnumnodes),cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixStressbalanceFSFriction{{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceFSFriction(void){
+
+	/*Intermediaries */
+	int         i,j;
+	int         analysis_type;
+	int         indices[2];
+	IssmDouble  alpha2,Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_seg[NUMVERTICES1D][3];
+	Friction   *friction = NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !HasEdgeOnBed()) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int  numdof   = vnumnodes*NDOF2 + pnumnodes*NDOF1;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke        = new ElementMatrix(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    BFriction = xNew<IssmDouble>(1*numdof);
+	IssmDouble     D;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Get vertex indices that lie on bed*/
+	this->EdgeOnBedIndices(&indices[0],&indices[1]);
+	for(i=0;i<NUMVERTICES1D;i++) for(j=0;j<2;j++) xyz_list_seg[i][j]=xyz_list[indices[i]][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("1d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 1d (nodes on the bedrock) */
+	GaussTria* gauss=new GaussTria(indices[0],indices[1],2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_seg[0][0],gauss);
+		GetLFS(BFriction,gauss);
+
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+		D = +alpha2*gauss->weight*Jdet; //taub_x = -alpha2 vx
+
+		TripleMultiply(BFriction,1,numdof,1,
+					&D,1,1,0,
+					BFriction,1,numdof,0,
+					Ke->values,1);
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+	//TransformStiffnessMatrixCoord(Ke,nodes,(vnumnodes+pnumnodes),cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(BFriction);
+	xDelete<int>(cs_list);
+	return Ke;
+}
+/*}}}*/
 /*FUNCTION Tria::CreateKMatrixStressbalanceSSA {{{*/
 ElementMatrix* Tria::CreateKMatrixStressbalanceSSA(void){
@@ -2994,5 +3532,4 @@
 
 	/*Intermediaries*/
-	int        i,j;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble viscosity,newviscosity,oldviscosity;
@@ -3038,5 +3575,5 @@
 		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
 		D_scalar=2.*newviscosity*thickness*gauss->weight*Jdet;
-		for(i=0;i<3;i++) D[i*3+i]=D_scalar;
+		for(int i=0;i<3;i++) D[i*3+i]=D_scalar;
 
 		TripleMultiply(B,3,numdof,1,
@@ -3062,5 +3599,4 @@
 	/*Intermediaries*/
 	bool       mainlyfloating;
-	int        i,j;
 	int        analysis_type,migration_style;
 	int        point1;
@@ -3092,5 +3628,4 @@
 	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* gllevelset_input=NULL;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -3125,5 +3660,5 @@
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		D_scalar=alpha2*gauss->weight*Jdet;
-		for(i=0;i<2;i++) D[i*2+i]=D_scalar;
+		for(int i=0;i<2;i++) D[i*2+i]=D_scalar;
 
 		TripleMultiply(B,2,numdof,1,
@@ -3166,4 +3701,242 @@
 	/*Clean up and return*/
 	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceFS {{{*/
+ElementVector* Tria::CreatePVectorStressbalanceFS(void){
+
+	ElementVector* pe1;
+	ElementVector* pe2;
+	ElementVector* pe3;
+	ElementVector* pe;
+
+	/*compute all stiffness matrices for this element*/
+	pe1=CreatePVectorStressbalanceFSViscous();
+	pe2=CreatePVectorStressbalanceFSShelf();
+	pe3=CreatePVectorStressbalanceFSFront();
+	pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceFSFront{{{*/
+ElementVector* Tria::CreatePVectorStressbalanceFSFront(void){
+
+	/*Intermediaries */
+	int         i;
+	IssmDouble  ls[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	bool        isfront;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is awlays <=0, there is no ice front here*/
+	isfront = false;
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]==0.)){
+			isfront = true;
+		}
+	}
+
+	/*If no front, return NULL*/
+	if(!isfront) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  rho_ice,rho_water,gravity,y_g;
+	IssmDouble  Jdet,water_pressure,air_pressure,pressure;
+	IssmDouble  xyz_list_front[2][3];
+	IssmDouble  area_coordinates[2][3];
+	IssmDouble  normal[2];
+	GaussTria*  gauss = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	rho_water = matpar->GetRhoWater();
+	gravity   = matpar->GetG();
+	GetZeroLevelsetCoordinates(&xyz_list_front[0][0],xyz_list,MaskIceLevelsetEnum);
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
+	GetSegmentNormal(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	IssmDouble ymax=max(xyz_list_front[0][1],xyz_list_front[1][1]);
+	IssmDouble ymin=min(xyz_list_front[0][1],xyz_list_front[1][1]);
+	if(ymax>0. && ymin<0.) gauss=new GaussTria(area_coordinates,30); //refined in vertical because of the sea level discontinuity
+	else                   gauss=new GaussTria(area_coordinates,3);
+
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		y_g=GetYcoord(gauss);
+		GetNodalFunctionsVelocity(vbasis,gauss);
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_front[0][0],gauss);
+
+		water_pressure = rho_water*gravity*min(0.,y_g); //0 if the gaussian point is above water level
+		air_pressure   = 0.;
+		pressure       = water_pressure + air_pressure;
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*vbasis[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*vbasis[i];
+		}
+	}
+
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,(vnumnodes+pnumnodes),cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	delete gauss;
+	return pe;
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceFSViscous {{{*/
+ElementVector* Tria::CreatePVectorStressbalanceFSViscous(void){
+
+	/*Intermediaries*/
+	int        i;
+	int        approximation;
+	IssmDouble Jdet,gravity,rho_ice;
+	IssmDouble forcex,forcey;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* loadingforcex_input=inputs->GetInput(LoadingforceXEnum);  _assert_(loadingforcex_input);
+	Input* loadingforcey_input=inputs->GetInput(LoadingforceYEnum);  _assert_(loadingforcey_input);
+	rho_ice = matpar->GetRhoIce();
+	gravity = matpar->GetG();
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsVelocity(vbasis, gauss);
+
+		loadingforcex_input->GetInputValue(&forcex,gauss);
+		loadingforcey_input->GetInputValue(&forcey,gauss);
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*NDOF2+1] += -rho_ice*gravity*Jdet*gauss->weight*vbasis[i];
+			pe->values[i*NDOF2+0] += +rho_ice*forcex *Jdet*gauss->weight*vbasis[i];
+			pe->values[i*NDOF2+1] += +rho_ice*forcey *Jdet*gauss->weight*vbasis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceFSShelf{{{*/
+ElementVector* Tria::CreatePVectorStressbalanceFSShelf(void){
+
+	/*Intermediaries*/
+	int         i,j;
+	int         indices[2];
+	IssmDouble  gravity,rho_water,bed,water_pressure;
+	IssmDouble  normal_vel,vx,vy,dt;
+	IssmDouble	xyz_list_seg[NUMVERTICES1D][3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble	normal[2];
+	IssmDouble  Jdet;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!HasEdgeOnBed() || !IsFloating()) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* bed_input=inputs->GetInput(BedEnum); _assert_(bed_input);
+
+	/*Get vertex indices that lie on bed*/
+	this->EdgeOnBedIndices(&indices[0],&indices[1]);
+
+	for(i=0;i<NUMVERTICES1D;i++) for(j=0;j<2;j++) xyz_list_seg[i][j]=xyz_list[indices[i]][j];
+
+	/* Start looping on the number of gauss 1d (nodes on the bedrock) */
+	GaussTria* gauss=new GaussTria(indices[0],indices[1],2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_seg[0][0],gauss);
+		GetNodalFunctionsVelocity(vbasis, gauss);
+
+		GetSegmentNormal(&normal[0],xyz_list_seg);
+		_assert_(normal[1]<0.);
+		bed_input->GetInputValue(&bed, gauss);
+		water_pressure=gravity*rho_water*bed;
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[2*i+0]+=(water_pressure)*gauss->weight*Jdet*vbasis[i]*normal[0];
+			pe->values[2*i+1]+=(water_pressure)*gauss->weight*Jdet*vbasis[i]*normal[1];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,(vnumnodes+pnumnodes),cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	return pe;
 }
 /*}}}*/
@@ -3195,5 +3968,4 @@
 	/*Fetch number of nodes and dof for this finite element*/
 	int numnodes = this->NumberofNodes();
-	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element vector and vectors*/
@@ -3328,5 +4100,4 @@
 	/*Fetch number of nodes and dof for this finite element*/
 	int numnodes = this->NumberofNodes(); _assert_(numnodes==3); 
-	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element vector*/
@@ -3385,5 +4156,4 @@
 	/*Fetch number of nodes and dof for this finite element*/
 	int numnodes = this->NumberofNodes();
-	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element matrix, vectors and Gaussian points*/
@@ -3436,4 +4206,59 @@
 }
 /*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsStressbalanceFS{{{*/
+void  Tria::GetSolutionFromInputsStressbalanceFS(Vector<IssmDouble>* solution){
+
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   vx,vy,p;
+	IssmDouble   FSreconditioning;
+	GaussTria   *gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*NDOF2;
+	int pnumdof   = pnumnodes*NDOF1;
+
+	/*Initialize values*/
+	IssmDouble* vvalues = xNew<IssmDouble>(vnumdof);
+	IssmDouble* pvalues = xNew<IssmDouble>(pnumdof);
+
+	/*Get dof list: */
+	GetDofListVelocity(&vdoflist,GsetEnum);
+	GetDofListPressure(&pdoflist,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* p_input =inputs->GetInput(PressureEnum); _assert_(p_input);
+
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	/*Ok, we have vx vy vz in values, fill in vx vy vz arrays: */
+	gauss = new GaussTria();
+	for(int i=0;i<vnumnodes;i++){
+		gauss->GaussNode(this->VelocityInterpolation(),i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vvalues[i*NDOF2+0]=vx;
+		vvalues[i*NDOF2+1]=vy;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		gauss->GaussNode(this->PressureInterpolation(),i);
+		p_input->GetInputValue(&p ,gauss);
+		pvalues[i]=p/FSreconditioning;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(vnumdof,vdoflist,vvalues,INS_VAL);
+	solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(pdoflist);
+	xDelete<int>(vdoflist);
+	xDelete<IssmDouble>(pvalues);
+	xDelete<IssmDouble>(vvalues);
+}
+/*}}}*/
 /*FUNCTION Tria::GetSolutionFromInputsStressbalanceHoriz{{{*/
 void  Tria::GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution){
@@ -3512,4 +4337,18 @@
 	delete gauss;
 	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::GetYcoord {{{*/
+IssmDouble Tria::GetYcoord(GaussTria* gauss){
+
+	IssmDouble y;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble y_list[NUMVERTICES];
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(int i=0;i<NUMVERTICES;i++) y_list[i]=xyz_list[i][1];
+	TriaRef::GetInputValue(&y,&y_list[0],gauss,P1Enum);
+
+	return y;
 }
 /*}}}*/
@@ -3586,4 +4425,81 @@
 }
 /*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionStressbalanceFS {{{*/
+void  Tria::InputUpdateFromSolutionStressbalanceFS(IssmDouble* solution){
+
+	int          i;
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   FSreconditioning;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*NDOF2;
+	int pnumdof   = pnumnodes*NDOF1;
+
+	/*Initialize values*/
+	IssmDouble* values   = xNew<IssmDouble>(vnumdof+pnumdof);
+	IssmDouble* vx       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vy       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vel      = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(pnumnodes);
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Get dof list: */
+	GetDofListVelocity(&vdoflist,GsetEnum);
+	GetDofListPressure(&pdoflist,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<vnumdof;i++) values[i]        =solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) values[vnumdof+i]=solution[pdoflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,vnumnodes+pnumdof,cs_list);
+
+	/*Ok, we have vx and vy in values, fill in all arrays: */
+	for(i=0;i<vnumnodes;i++){
+		vx[i] = values[i*NDOF2+0];
+		vy[i] = values[i*NDOF2+1];
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+	for(i=0;i<pnumnodes;i++){
+		pressure[i] = values[vnumdof+i];
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<pnumnodes;i++) pressure[i] = pressure[i]*FSreconditioning;
+	for(i=0;i<vnumnodes;i++) vel[i]      = sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
+
+	/*Now, we have to move the previous inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	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 TriaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new TriaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new TriaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new TriaInput(PressureEnum,pressure,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<int>(vdoflist);
+	xDelete<int>(pdoflist);
+	xDelete<int>(cs_list);
+}
+/*}}}*/
 /*FUNCTION Tria::InputUpdateFromSolutionStressbalanceSIA {{{*/
 void  Tria::InputUpdateFromSolutionStressbalanceSIA(IssmDouble* solution){
@@ -3661,5 +4577,5 @@
 #ifdef _HAVE_CONTROL_
 /*FUNCTION Tria::BalancethicknessMisfit{{{*/
-IssmDouble Tria::BalancethicknessMisfit(int weight_index){
+IssmDouble Tria::BalancethicknessMisfit(void){
 
 	/* Intermediaries */
@@ -3697,5 +4613,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,BalancethicknessMisfitEnum);
 		thickness_input->GetInputValue(&H, gauss);
 		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
@@ -3732,5 +4648,5 @@
 	for(int i=0;i<num_controls;i++){
 
-		if(control_type[i]==MaterialsRheologyBbarEnum || control_type[i]==MaterialsRheologyZbarEnum){
+		if(control_type[i]==MaterialsRheologyBbarEnum || control_type[i]==DamageDbarEnum){
 			input=(Input*)material->inputs->GetInput(control_type[i]); _assert_(input);
 		}
@@ -3759,5 +4675,5 @@
 	Input* input=NULL;
 
-	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==DamageDbarEnum){
 		input=(Input*)material->inputs->GetInput(enum_type);
 	}
@@ -3777,5 +4693,5 @@
 	Input* input=NULL;
 
-	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==DamageDbarEnum){
 		input=(Input*)material->inputs->GetInput(enum_type);
 	}
@@ -3796,5 +4712,5 @@
 	Input* input=NULL;
 
-	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==DamageDbarEnum){
 		input=(Input*)material->inputs->GetInput(enum_type);
 	}
@@ -3810,4 +4726,42 @@
 
 	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Tria::ControlToVectors{{{*/
+void Tria::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){
+
+	Input* input=NULL;
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==DamageDbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum);
+	}
+	else{
+		input=inputs->GetInput(control_enum);
+	}
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetConnectivityList(&connectivity[0]);
+	this->GetVertexSidList(&sidlist[0]);
+
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
 
 }/*}}}*/
@@ -3827,6 +4781,6 @@
 			GradjBSSA(gradient,control_index);
 			break;
-		case MaterialsRheologyZbarEnum:
-			GradjZSSA(gradient,control_index);
+		case DamageDbarEnum:
+			GradjDSSA(gradient,control_index);
 			break;
 		case BalancethicknessThickeningRateEnum:
@@ -3850,5 +4804,5 @@
 	int         num_responses,resp;
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 
 	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
@@ -3868,8 +4822,8 @@
 			break;
 		case DragCoefficientAbsGradientEnum:
-			GradjDragGradient(gradient,resp,control_index);
+			GradjDragGradient(gradient,control_index);
 			break;
 		case RheologyBbarAbsGradientEnum:
-			GradjBGradient(gradient,resp,control_index);
+			GradjBGradient(gradient,control_index);
 			break;
 		default:
@@ -3881,5 +4835,5 @@
 /*}}}*/
 /*FUNCTION Tria::GradjBGradient{{{*/
-void  Tria::GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
+void  Tria::GradjBGradient(Vector<IssmDouble>* gradient,int control_index){
 
 	int        i;
@@ -3906,48 +4860,8 @@
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
 
 		/*Build alpha_complement_list: */
 		rheologyb_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
-/*FUNCTION Tria::GradjZGradient{{{*/
-void  Tria::GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
-
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble Jdet,weight;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dbasis[NDOF2][NUMVERTICES];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	GaussTria  *gauss=NULL;
-
-	/*Retrieve all inputs we will be needing: */
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
-	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,weight_index);
-
-		/*Build alpha_complement_list: */
-		rheologyz_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
 
 		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
@@ -4017,6 +4931,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GradjZSSA{{{*/
-void  Tria::GradjZSSA(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Tria::GradjDSSA{{{*/
+void  Tria::GradjDSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Intermediaries*/
@@ -4025,5 +4939,5 @@
 	IssmDouble vx,vy,lambda,mu,thickness,Jdet;
 	IssmDouble viscosity_complement;
-	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dZ[NDOF2]; 
+	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2];
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble basis[3],epsilon[3];
@@ -4041,5 +4955,5 @@
 	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                       _assert_(adjointx_input);
 	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                       _assert_(adjointy_input);
-	Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
+	Input* rheologyd_input=material->inputs->GetInput(DamageDbarEnum); _assert_(rheologyd_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -4050,5 +4964,4 @@
 
 		thickness_input->GetInputValue(&thickness,gauss);
-		rheologyz_input->GetInputDerivativeValue(&dZ[0],&xyz_list[0][0],gauss);
 		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
 		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
@@ -4057,5 +4970,5 @@
 
 		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		material->GetViscosityZComplement(&viscosity_complement,&epsilon[0]);
+		material->GetViscosityDComplement(&viscosity_complement,&epsilon[0]);
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
@@ -4088,5 +5001,4 @@
 	IssmDouble grade_g_gaussian[NUMVERTICES];
 	IssmDouble basis[3];
-	IssmDouble epsilon[3]; /* epsilon=[exx,eyy,exy];*/
 	Friction*  friction=NULL;
 	GaussTria  *gauss=NULL;
@@ -4163,5 +5075,5 @@
 /*}}}*/
 /*FUNCTION Tria::GradjDragGradient{{{*/
-void  Tria::GradjDragGradient(Vector<IssmDouble>* gradient, int weight_index,int control_index){
+void  Tria::GradjDragGradient(Vector<IssmDouble>* gradient,int control_index){
 
 	int        i;
@@ -4189,5 +5101,5 @@
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
 
 		/*Build alpha_complement_list: */
@@ -4334,5 +5246,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 	Input* thickness_input            = inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
 	Input* thicknessobs_input         = inputs->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
@@ -4359,51 +5271,51 @@
 
 		/*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<NUMVERTICES;i++) grade_g[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
-				break;
-			case ThicknessAbsGradientEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
-				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
-				break;
-			case ThicknessAlongGradientEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&vx,gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				vel = sqrt(vx*vx+vy*vy);
-				vx  = vx/(vel+1.e-9);
-				vy  = vy/(vel+1.e-9);
-				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
-				break;
-			case ThicknessAcrossGradientEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&vx,gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				vel = sqrt(vx*vx+vy*vy);
-				vx  = vx/(vel+1.e-9);
-				vy  = vy/(vel+1.e-9);
-				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
-				break;
-			case BalancethicknessMisfitEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
-				basal_melting_input->GetInputValue(&basal_melting,gauss);
-				dhdt_input->GetInputValue(&dhdt,gauss);
-				vx_input->GetInputValue(&vx,gauss);
-				vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
-				for(i=0;i<NUMVERTICES;i++){
-					grade_g[i]+= - weight*Jdet*gauss->weight*(
-								(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
-								-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
-								);
-				}
-				break;
-			default:
-				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+
+				case ThicknessAbsMisfitEnum:
+					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case ThicknessAbsGradientEnum:
+					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
+					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
+					break;
+				case ThicknessAlongGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
+					break;
+				case ThicknessAcrossGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
+					break;
+				case BalancethicknessMisfitEnum:
+					surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+					basal_melting_input->GetInputValue(&basal_melting,gauss);
+					dhdt_input->GetInputValue(&dhdt,gauss);
+					vx_input->GetInputValue(&vx,gauss);
+					vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+					for(i=0;i<NUMVERTICES;i++){
+						grade_g[i]+= - weight*Jdet*gauss->weight*(
+									(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
+									-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
+									);
+					}
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
 		}
 	}
@@ -4431,5 +5343,5 @@
 /*}}}*/
 /*FUNCTION Tria::RheologyBbarAbsGradient{{{*/
-IssmDouble Tria::RheologyBbarAbsGradient(int weight_index){
+IssmDouble Tria::RheologyBbarAbsGradient(void){
 
 	/* Intermediaries */
@@ -4461,5 +5373,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
 		rheologyb_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
 
@@ -4474,5 +5386,5 @@
 /*}}}*/
 /*FUNCTION Tria::SurfaceAverageVelMisfit {{{*/
-IssmDouble Tria::SurfaceAverageVelMisfit(int weight_index){
+IssmDouble Tria::SurfaceAverageVelMisfit(void){
 
 	IssmDouble Jelem=0,S,Jdet;
@@ -4506,5 +5418,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,SurfaceAverageVelMisfitEnum);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -4530,5 +5442,5 @@
 /*}}}*/
 /*FUNCTION Tria::SurfaceLogVelMisfit {{{*/
-IssmDouble Tria::SurfaceLogVelMisfit(int weight_index){
+IssmDouble Tria::SurfaceLogVelMisfit(void){
 
 	IssmDouble Jelem=0.;
@@ -4564,5 +5476,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,SurfaceLogVelMisfitEnum);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -4590,7 +5502,6 @@
 /*}}}*/
 /*FUNCTION Tria::SurfaceLogVxVyMisfit {{{*/
-IssmDouble Tria::SurfaceLogVxVyMisfit(int weight_index){
-
-	int        fit=-1;
+IssmDouble Tria::SurfaceLogVxVyMisfit(void){
+
 	IssmDouble Jelem=0, S=0;
 	IssmDouble epsvel=2.220446049250313e-16;
@@ -4624,5 +5535,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,SurfaceLogVxVyMisfitEnum);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -4651,5 +5562,5 @@
 /*}}}*/
 /*FUNCTION Tria::SurfaceAbsVelMisfit {{{*/
-IssmDouble Tria::SurfaceAbsVelMisfit(int weight_index){
+IssmDouble Tria::SurfaceAbsVelMisfit(void){
 
 	IssmDouble Jelem=0;
@@ -4682,5 +5593,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,SurfaceAbsVelMisfitEnum);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -4707,5 +5618,5 @@
 /*}}}*/
 /*FUNCTION Tria::SurfaceRelVelMisfit {{{*/
-IssmDouble Tria::SurfaceRelVelMisfit(int weight_index){
+IssmDouble Tria::SurfaceRelVelMisfit(void){
 
 	IssmDouble  Jelem=0;
@@ -4741,5 +5652,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,SurfaceRelVelMisfitEnum);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -4768,5 +5679,5 @@
 /*}}}*/
 /*FUNCTION Tria::ThicknessAbsGradient{{{*/
-IssmDouble Tria::ThicknessAbsGradient(int weight_index){
+IssmDouble Tria::ThicknessAbsGradient(void){
 
 	/* Intermediaries */
@@ -4798,5 +5709,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,ThicknessAbsGradientEnum);
 		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
 
@@ -4811,5 +5722,5 @@
 /*}}}*/
 /*FUNCTION Tria::ThicknessAlongGradient{{{*/
-IssmDouble Tria::ThicknessAlongGradient(int weight_index){
+IssmDouble Tria::ThicknessAlongGradient(void){
 
 	/* Intermediaries */
@@ -4844,5 +5755,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,ThicknessAlongGradientEnum);
 		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
 		vx_input->GetInputValue(&vx,gauss);
@@ -4862,5 +5773,5 @@
 /*}}}*/
 /*FUNCTION Tria::ThicknessAcrossGradient{{{*/
-IssmDouble Tria::ThicknessAcrossGradient(int weight_index){
+IssmDouble Tria::ThicknessAcrossGradient(void){
 
 	/* Intermediaries */
@@ -4895,5 +5806,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,ThicknessAcrossGradientEnum);
 		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
 		vx_input->GetInputValue(&vx,gauss);
@@ -4913,5 +5824,5 @@
 /*}}}*/
 /*FUNCTION Tria::ThicknessAbsMisfit {{{*/
-IssmDouble Tria::ThicknessAbsMisfit(int weight_index){
+IssmDouble Tria::ThicknessAbsMisfit(void){
 
 	/*Intermediaries*/
@@ -4945,5 +5856,5 @@
 		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
 		thicknessobs_input->GetInputValue(&thicknessobs,gauss);
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,ThicknessAbsMisfitEnum);
 
 		/*compute ThicknessAbsMisfit*/
@@ -4980,5 +5891,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 	Input* thickness_input    = inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
 	Input* thicknessobs_input = inputs->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
@@ -5002,35 +5913,35 @@
 
 		/*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<numnodes;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<numnodes;i++) pe->values[i]+= - weight*dH[0]*dbasis[0*numnodes+i]*Jdet*gauss->weight;
-				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[1]*dbasis[1*numnodes+i]*Jdet*gauss->weight;
-				break;
-			case ThicknessAlongGradientEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&vx,gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				vel = sqrt(vx*vx+vy*vy);
-				vx  = vx/(vel+1.e-9);
-				vy  = vy/(vel+1.e-9);
-				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numnodes+i]*vx+dbasis[1*numnodes+i]*vy)*Jdet*gauss->weight;
-				break;
-			case ThicknessAcrossGradientEnum:
-				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&vx,gauss);
-				vy_input->GetInputValue(&vy,gauss);
-				vel = sqrt(vx*vx+vy*vy);
-				vx  = vx/(vel+1.e-9);
-				vy  = vy/(vel+1.e-9);
-				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numnodes+i]*(-vy)+dbasis[1*numnodes+i]*vx)*Jdet*gauss->weight;
-				break;
-			default:
-				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case ThicknessAbsMisfitEnum:
+					for(i=0;i<numnodes;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case ThicknessAbsGradientEnum:
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[0]*dbasis[0*numnodes+i]*Jdet*gauss->weight;
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[1]*dbasis[1*numnodes+i]*Jdet*gauss->weight;
+					break;
+				case ThicknessAlongGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numnodes+i]*vx+dbasis[1*numnodes+i]*vy)*Jdet*gauss->weight;
+					break;
+				case ThicknessAcrossGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numnodes+i]*(-vy)+dbasis[1*numnodes+i]*vx)*Jdet*gauss->weight;
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
 		}
 	}
@@ -5070,5 +5981,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
 	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
@@ -5103,5 +6014,5 @@
 		for(resp=0;resp<num_responses;resp++){
 
-			weights_input->GetInputValue(&weight,gauss,resp);
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
 
 			switch(responses[resp]){
@@ -5230,5 +6141,5 @@
 /*}}}*/
 /*FUNCTION Tria::DragCoefficientAbsGradient{{{*/
-IssmDouble Tria::DragCoefficientAbsGradient(int weight_index){
+IssmDouble Tria::DragCoefficientAbsGradient(void){
 
 	/* Intermediaries */
@@ -5260,5 +6171,5 @@
 
 		/*Get all parameters at gaussian point*/
-		weights_input->GetInputValue(&weight,gauss,weight_index);
+		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
 		drag_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
 
@@ -5422,5 +6333,5 @@
 
 	/*Get input (either in element or material)*/
-	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==DamageDbarEnum){
 		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
 	}
@@ -5457,5 +6368,5 @@
 	new_input = new TriaInput(control_enum,values,P1Enum);
 
-	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==DamageDbarEnum){
 		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
 	}
@@ -5610,5 +6521,5 @@
 
 	/*Skip if water or ice shelf element*/
-	if(NoIceInElement() | IsFloating()) return NULL;
+	if(NoIceInElement() || IsFloating()) return NULL;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -5835,5 +6746,5 @@
 
 	/*Skip if water or ice shelf element*/
-	if(NoIceInElement() | IsFloating()) return NULL;
+	if(NoIceInElement() || IsFloating()) return NULL;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -6309,4 +7220,161 @@
 
 #ifdef _HAVE_MASSTRANSPORT_
+/*FUNCTION Tria::CreateKMatrixExtrusion {{{*/
+ElementMatrix* Tria::CreateKMatrixExtrusion(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixExtrusionVolume();
+	ElementMatrix* Ke2=CreateKMatrixExtrusionSurface();
+	ElementMatrix* Ke3=CreateKMatrixExtrusionBed();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixExtrusionVolume {{{*/
+ElementMatrix* Tria::CreateKMatrixExtrusionVolume(void){
+
+	/*Intermediaries */
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[NDOF1][NUMVERTICES];
+	IssmDouble  Bprime[NDOF1][NUMVERTICES];
+	IssmDouble  DL_scalar;
+	GaussTria  *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBExtrusion(&B[0][0], &xyz_list[0][0], gauss);
+		GetNodalFunctions(&Bprime[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 Tria::CreateKMatrixExtrusionSurface {{{*/
+ElementMatrix* Tria::CreateKMatrixExtrusionSurface(void){
+
+	if (!HasEdgeOnSurface()) return NULL;
+
+	/*Constants*/
+	const int numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_seg[NUMVERTICES1D][3];
+	IssmDouble normal[3];
+	IssmDouble Jdet,DL_scalar;
+	IssmDouble basis[NUMVERTICES];
+	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],vertices,NUMVERTICES);
+
+	/*Get vertex indices that lie on bed*/
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+	for(int i=0;i<NUMVERTICES1D;i++) for(int j=0;j<2;j++) xyz_list_seg[i][j]=xyz_list[indices[i]][j];
+	GetSegmentNormal(&normal[0],xyz_list_seg);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(indices[0],indices[1],2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_seg[0][0],gauss);
+		GetNodalFunctions(&basis[0], gauss);
+
+		DL_scalar= - gauss->weight*Jdet*normal[1]; 
+
+		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 Tria::CreateKMatrixExtrusionBed {{{*/
+ElementMatrix* Tria::CreateKMatrixExtrusionBed(void){
+
+	if (!HasEdgeOnBed()) return NULL;
+
+	/*Constants*/
+	const int numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_seg[NUMVERTICES1D][3];
+	IssmDouble normal[3];
+	IssmDouble Jdet,DL_scalar;
+	IssmDouble basis[NUMVERTICES];
+	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],vertices,NUMVERTICES);
+
+	/*Get vertex indices that lie on bed*/
+	this->EdgeOnBedIndices(&indices[0],&indices[1]);
+	for(int i=0;i<NUMVERTICES1D;i++) for(int j=0;j<2;j++) xyz_list_seg[i][j]=xyz_list[indices[i]][j];
+	GetSegmentNormal(&normal[0],xyz_list_seg);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(indices[0],indices[1],2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_seg[0][0],gauss);
+		GetNodalFunctions(&basis[0], gauss);
+
+		DL_scalar= - gauss->weight*Jdet*normal[1]; 
+
+		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 Tria::CreateKMatrixMasstransport {{{*/
 ElementMatrix* Tria::CreateKMatrixMasstransport(void){
@@ -6327,5 +7395,5 @@
 	/*Intermediaries */
 	int        stabilization;
-	int        dim;
+	int        meshtype;
 	IssmDouble Jdet,D_scalar,dt,h;
 	IssmDouble vel,vx,vy,dvxdx,dvydy;
@@ -6346,9 +7414,9 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
 	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
 	Input* vxaverage_input=NULL;
 	Input* vyaverage_input=NULL;
-	if(dim==2){
+	if(meshtype==Mesh2DhorizontalEnum){
 		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
 		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
@@ -6445,5 +7513,5 @@
 
 	/*Intermediaries */
-	int        dim;
+	int        meshtype;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble Jdet,D_scalar,dt,vx,vy;
@@ -6462,8 +7530,8 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
 	Input* vxaverage_input=NULL;
 	Input* vyaverage_input=NULL;
-	if(dim==2){
+	if(meshtype==Mesh2DhorizontalEnum){
 		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
 		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
@@ -6522,5 +7590,4 @@
 	/*Intermediaries */
 	int        stabilization;
-	int        dim;
 	IssmDouble Jdet,D_scalar,dt,h;
 	IssmDouble vel,vx,vy;
@@ -6615,4 +7682,20 @@
 }
 /*}}}*/
+/*FUNCTION Tria::CreateKMatrixFreeSurfaceTop1D {{{*/
+ElementMatrix* Tria::CreateKMatrixFreeSurfaceTop1D(void){
+
+	if(!HasEdgeOnSurface()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnSurfaceIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementMatrix* Ke=seg->CreateKMatrixFreeSurfaceTop();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
 /*FUNCTION Tria::CreateKMatrixFreeSurfaceBase {{{*/
 ElementMatrix* Tria::CreateKMatrixFreeSurfaceBase(void){
@@ -6620,5 +7703,4 @@
 	/*Intermediaries */
 	int        stabilization;
-	int        dim;
 	IssmDouble Jdet,D_scalar,dt,h;
 	IssmDouble vel,vx,vy;
@@ -6713,4 +7795,20 @@
 }
 /*}}}*/
+/*FUNCTION Tria::CreateKMatrixFreeSurfaceBase1D {{{*/
+ElementMatrix* Tria::CreateKMatrixFreeSurfaceBase1D(void){
+
+	if(!HasEdgeOnBed()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnBedIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementMatrix* Ke=seg->CreateKMatrixFreeSurfaceBase();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
 /*FUNCTION Tria::CreatePVectorMasstransport{{{*/
 ElementVector* Tria::CreatePVectorMasstransport(void){
@@ -6865,4 +7963,20 @@
 }
 /*}}}*/
+/*FUNCTION Tria::CreatePVectorFreeSurfaceTop1D {{{*/
+ElementVector* Tria::CreatePVectorFreeSurfaceTop1D(void){
+
+	if(!HasEdgeOnSurface()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnSurfaceIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementVector* pe=seg->CreatePVectorFreeSurfaceTop();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
 /*FUNCTION Tria::CreatePVectorFreeSurfaceBase {{{*/
 ElementVector* Tria::CreatePVectorFreeSurfaceBase(void){
@@ -6913,4 +8027,313 @@
 	delete gauss;
 	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorFreeSurfaceBase1D {{{*/
+ElementVector* Tria::CreatePVectorFreeSurfaceBase1D(void){
+
+	if(!HasEdgeOnBed()) return NULL;
+
+	int index1,index2;
+	this->EdgeOnBedIndices(&index1,&index2);
+
+	Seg* seg=(Seg*)SpawnSeg(index1,index2); 
+	ElementVector* pe=seg->CreatePVectorFreeSurfaceBase();
+	delete seg->material; delete seg;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAMAGE_
+/*FUNCTION Tria::CreateKMatrixDamageEvolution {{{*/
+ElementMatrix* Tria::CreateKMatrixDamageEvolution(void){
+
+	switch(GetElementType()){
+		case P1Enum: case P2Enum:
+			return CreateKMatrixDamageEvolution_CG();
+		case P1DGEnum:
+			_error_("DG not implemented yet!");break;
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDamageEvolution_CG {{{*/
+ElementMatrix* Tria::CreateKMatrixDamageEvolution_CG(void){
+
+	/*Intermediaries */
+	int        stabilization;
+	int        meshtype;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vel,vx,vy,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
+	this->parameters->FindParam(&stabilization,DamageStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(meshtype==Mesh2DhorizontalEnum){
+		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: */
+	GaussTria *gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,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);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+		GetBMasstransport(B,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=sqrt(vx*vx+vy*vy)+1.e-8;
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDamageEvolution{{{*/
+ElementVector* Tria::CreatePVectorDamageEvolution(void){
+
+	switch(GetElementType()){
+		case P1Enum: case P2Enum:
+			return CreatePVectorDamageEvolution_CG();
+		case P1DGEnum:
+			_error_("DG not implemented yet");
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDamageEvolution_CG {{{*/
+ElementVector* Tria::CreatePVectorDamageEvolution_CG(void){
+
+	/*Intermediaries */
+	IssmDouble  Jdet ,dt;
+	IssmDouble  f,damage;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  f_list[NUMVERTICES];
+	Input      *damage_input             = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	damage_input  = this->material->inputs->GetInput(DamageDbarEnum);     _assert_(damage_input);
+	
+	/*retrieve damage evolution forcing function: */
+	this->DamageEvolutionF(&f_list[0]);
+
+	/*Initialize forcing function f to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		TriaRef::GetInputValue(&f,f_list,gauss);
+		damage_input->GetInputValue(&damage,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(damage+dt*f)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::DamageEvolutionF{{{*/
+void Tria::DamageEvolutionF(IssmDouble* f){
+
+	/*Intermediaries */
+	IssmDouble c1,c2,c3,healing,stress_threshold;
+	IssmDouble s_xx,s_xy,s_yy;
+	IssmDouble J2s;
+	IssmDouble Xis;
+	IssmDouble Psi;
+	IssmDouble PosPsi;
+	IssmDouble NegPsi;
+	Input* damage_input=NULL;
+	Input* sigma_xx_input  = NULL;
+	Input* sigma_xy_input  = NULL;
+	Input* sigma_yy_input  = NULL;
+	GaussTria* gauss=NULL;
+	IssmDouble damage,sigma_xx,sigma_xy,sigma_yy;
+
+	/*retrieve parameters:*/
+	this->parameters->FindParam(&c1,DamageC1Enum);
+	this->parameters->FindParam(&c2,DamageC2Enum);
+	this->parameters->FindParam(&c3,DamageC3Enum);
+	this->parameters->FindParam(&healing,DamageHealingEnum);
+	this->parameters->FindParam(&stress_threshold,DamageStressThresholdEnum);
+
+	/*Compute stress tensor: */
+	this->ComputeStressTensor();
+
+	/*retrieve what we need: */
+	sigma_xx_input  = inputs->GetInput(StressTensorxxEnum);  _assert_(sigma_xx_input);
+	sigma_xy_input  = inputs->GetInput(StressTensorxyEnum);  _assert_(sigma_xy_input);
+	sigma_yy_input  = inputs->GetInput(StressTensoryyEnum);  _assert_(sigma_yy_input);
+	damage_input  = this->material->inputs->GetInput(DamageDbarEnum);        _assert_(damage_input);
+
+	/*Damage evolution z mapping: */
+	gauss=new GaussTria();
+	J2s=0;
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		
+		damage_input->GetInputValue(&damage,gauss);
+		sigma_xx_input->GetInputValue(&sigma_xx,gauss);
+		sigma_xy_input->GetInputValue(&sigma_xy,gauss);
+		sigma_yy_input->GetInputValue(&sigma_yy,gauss);
+
+		s_xx=sigma_xx/(1-damage);
+		s_xy=sigma_xy/(1-damage);
+		s_yy=sigma_yy/(1-damage);
+
+		J2s=1.0/sqrt(2.0)*sqrt(pow(s_xx,2)+pow(s_yy,2)+2*pow(s_xy,2));
+		
+		Xis=sqrt(3.0)*J2s;
+
+		Psi=Xis-stress_threshold;
+
+		PosPsi=max(Psi,0.0);
+		NegPsi=max(-Psi,0.0);
+
+		f[iv]= c1* ( pow(PosPsi,c2)   -  healing * pow(NegPsi,c2) )  *   pow((1 - damage),-c3);
+
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDamageEvolution {{{*/
+void  Tria::InputUpdateFromSolutionDamageEvolution(IssmDouble* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int         i;
+	IssmDouble  values[numdof];
+	IssmDouble  max_damage;
+	int			*doflist = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get user-supplied max_damage: */
+	this->parameters->FindParam(&max_damage,DamageMaxDamageEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		/*Enforce D < max_damage and D > 0 */
+		if(values[i]>max_damage) values[i]=max_damage;
+		else if(values[i]<0) values[i]=0;
+	}
+
+	/*Get all inputs and parameters*/
+	this->material->inputs->AddInput(new TriaInput(DamageDbarEnum,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
 }
 /*}}}*/
@@ -7067,6 +8490,5 @@
 
 	/*Intermediaries */
-	int        stabilization;
-	int        i,j,dim;
+	int        stabilization,meshtype;
 	IssmDouble Jdet,vx,vy,dvxdx,dvydy,vel,h;
 	IssmDouble D_scalar;
@@ -7087,8 +8509,8 @@
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&stabilization,BalancethicknessStabilizationEnum);
-	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&meshtype,MeshTypeEnum);
 	Input* vxaverage_input=NULL;
 	Input* vyaverage_input=NULL;
-	if(dim==2){
+	if(meshtype==Mesh2DhorizontalEnum){
 		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
 		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
@@ -7176,5 +8598,4 @@
 
 	/*Intermediaries*/
-	int        dim;
 	IssmDouble vx,vy,D_scalar,Jdet;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -7192,5 +8613,4 @@
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&dim,MeshDimensionEnum);
 	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
@@ -7316,5 +8736,4 @@
 	IssmDouble D_scalar,Jdet,thickness;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble D[2][2];
 	IssmDouble l=8.;
 
@@ -7556,6 +8975,4 @@
 	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
 	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
-	IssmDouble*    Vx     = xNew<IssmDouble>(numnodes);
-	IssmDouble*    Vy     = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -7661,5 +9078,4 @@
 	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
 	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
-	bool       grounded[NUMVERTICES],floating[NUMVERTICES];
 
 	/*Recover info at the vertices: */
@@ -7684,6 +9100,4 @@
 				b[i]        = r[i];
 				s[i]        = b[i]+h[i];
-				floating[i] = false;
-				grounded[i] = true;
 			}
 		}
@@ -7697,12 +9111,8 @@
 					s[i]        = (1-density)*h[i];
 					b[i]        = -density*h[i];
-					floating[i] = true;
-					grounded[i] = false;
 				}
 				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
 					s[i]        = (1-density)*h[i];
 					b[i]        = -density*h[i];
-					floating[i] = true;
-					grounded[i] = false;
 				}
 				else{
Index: /issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/Tria.h	(revision 16560)
@@ -18,4 +18,5 @@
 class Material;
 class Matpar;
+class Seg;
 class ElementMatrix;
 class ElementVector;
@@ -40,5 +41,4 @@
 		Parameters  *parameters;                  //pointer to solution parameters
 		Inputs      *inputs;
-		Results     *results;
 
 		/*Tria constructors, destructors {{{*/
@@ -84,4 +84,10 @@
 		int         Sid();
 		bool        IsOnBed();
+		bool        HasEdgeOnBed();
+		bool        HasEdgeOnSurface();
+		void        EdgeOnSurfaceIndices(int* pindex1,int* pindex);
+		void        EdgeOnBedIndices(int* pindex1,int* pindex);
+		int         EdgeOnBedIndex();
+		int         EdgeOnSurfaceIndex();
 		bool        IsFloating();
 		bool        IsNodeOnShelfFromFlags(IssmDouble* flags);
@@ -89,21 +95,14 @@
 		void        GetSolutionFromInputs(Vector<IssmDouble>* solution);
 		void        GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
-		void        GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp);
-		void        InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
-		void        InputCreate(IssmDouble scalar,int name,int code);
-		void        InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void        InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
 		void        InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
 		void        InputDuplicate(int original_enum,int new_enum);
 		void        InputScale(int enum_type,IssmDouble scale_factor);
-		void        InputToResult(int enum_type,int step,IssmDouble time);
-		void        DeleteResults(void);
 		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
 		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
 		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
-		void        RequestedOutput(int output_enum,int step,IssmDouble time);
-		void        ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results);
-		void        PatchFill(int* pcount, Patch* patch);
-		void        PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
-		void        ResetCoordinateSystem(void){_error_("not implemented yet");};
+		void        ResultInterpolation(int* pinterpolation,int output_enum);
+		void        ResultToVector(Vector<IssmPDouble>* vector,int output_enum);
+		void        ResetCoordinateSystem(void);
 		void	      SmbGradients();
 		IssmDouble  SurfaceArea(void);
@@ -114,4 +113,5 @@
 		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
 		IssmDouble IceVolume(void);
+		IssmDouble IceVolumeAboveFloatation(void);
 		IssmDouble TotalSmb(void);
 		void       MinVel(IssmDouble* pminvel);
@@ -120,4 +120,5 @@
 		void       MinVz(IssmDouble* pminvz);
 		IssmDouble MassFlux(IssmDouble* segment);
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
 		void       MaxAbsVx(IssmDouble* pmaxabsvx);
 		void       MaxAbsVy(IssmDouble* pmaxabsvy);
@@ -135,14 +136,14 @@
 
 		#ifdef _HAVE_CONTROL_
-		IssmDouble DragCoefficientAbsGradient(int weight_index);
+		IssmDouble DragCoefficientAbsGradient(void);
 		void       GradientIndexing(int* indexing,int control_index);
 		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
-		void       GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
-		void       GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void       GradjBGradient(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjDGradient(Vector<IssmDouble>* gradient,int control_index);
 		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjZSSA(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjDSSA(Vector<IssmDouble>* gradient,int control_index);
 		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index);
 		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDragGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void       GradjDragGradient(Vector<IssmDouble>* gradient,int control_index);
 		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
 		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
@@ -154,15 +155,16 @@
 		void       ControlInputScaleGradient(int enum_type,IssmDouble scale);
 		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
-		IssmDouble RheologyBbarAbsGradient(int weight_index);
-		IssmDouble ThicknessAbsMisfit(     int weight_index);
-		IssmDouble SurfaceAbsVelMisfit(    int weight_index);
-		IssmDouble ThicknessAbsGradient(   int weight_index);
-		IssmDouble ThicknessAlongGradient( int weight_index);
-		IssmDouble ThicknessAcrossGradient(int weight_index);
-		IssmDouble BalancethicknessMisfit(     int weight_index);
-		IssmDouble SurfaceRelVelMisfit(    int weight_index);
-		IssmDouble SurfaceLogVelMisfit(    int weight_index);
-		IssmDouble SurfaceLogVxVyMisfit(   int weight_index);
-		IssmDouble SurfaceAverageVelMisfit(int weight_index);
+		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
+		IssmDouble RheologyBbarAbsGradient(void);
+		IssmDouble ThicknessAbsMisfit(void);
+		IssmDouble SurfaceAbsVelMisfit(void);
+		IssmDouble ThicknessAbsGradient(void);
+		IssmDouble ThicknessAlongGradient(void);
+		IssmDouble ThicknessAcrossGradient(void);
+		IssmDouble BalancethicknessMisfit(void);
+		IssmDouble SurfaceRelVelMisfit(void);
+		IssmDouble SurfaceLogVelMisfit(void);
+		IssmDouble SurfaceLogVxVyMisfit(void);
+		IssmDouble SurfaceAverageVelMisfit(void);
 		void       InputControlUpdate(IssmDouble scalar,bool save_parameter);
 		#endif
@@ -186,7 +188,14 @@
 		ElementMatrix* CreateKMatrixMasstransport_CG(void);
 		ElementMatrix* CreateKMatrixMasstransport_DG(void);
+		ElementMatrix* CreateKMatrixExtrusion(void);
+		ElementMatrix* CreateKMatrixExtrusionVolume(void);
+		ElementMatrix* CreateKMatrixExtrusionSurface(void);
+		ElementMatrix* CreateKMatrixExtrusionBed(void);
 		ElementMatrix* CreateKMatrixFreeSurfaceTop(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceTop1D(void);
 		ElementMatrix* CreateKMatrixFreeSurfaceBase(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceBase1D(void);
 		ElementMatrix* CreateMassMatrix(void);
+		ElementMatrix* CreateBasalMassMatrix(void);
 		ElementVector* CreatePVector(void);
 		ElementVector* CreatePVectorBalancethickness(void);
@@ -200,10 +209,15 @@
 		ElementVector* CreatePVectorMasstransport_DG(void);
 		ElementVector* CreatePVectorFreeSurfaceTop(void);
+		ElementVector* CreatePVectorFreeSurfaceTop1D(void);
 		ElementVector* CreatePVectorFreeSurfaceBase(void);
-		ElementVector* CreatePVectorSlope(void);
+		ElementVector* CreatePVectorFreeSurfaceBase1D(void);
+		ElementVector* CreatePVectorL2Projection(void);
+		ElementVector* CreatePVectorL2ProjectionBase(void);
 		IssmDouble     GetArea(void);
 		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble xyz_zero[3][3],IssmDouble xyz_list[3][3],int numpoints);
 		int            GetElementType(void);
 		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         GetDofListVelocity(int** pdoflist,int setenum);
+		void	         GetDofListPressure(int** pdoflist,int setenum);
 		void	         GetVertexPidList(int* doflist);
 		void           GetVertexSidList(int* sidlist);
@@ -219,4 +233,5 @@
 		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
 		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void           GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype);
 		void           GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input);
 		void	         InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type);
@@ -224,4 +239,5 @@
 		bool	         IsInput(int name);
 		void	         SetClone(int* minranks);
+		Seg*	         SpawnSeg(int index1,int index2);
 		void	         SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
 
@@ -231,13 +247,24 @@
 		ElementMatrix* CreateKMatrixStressbalanceSSAFriction(void);
 		ElementMatrix* CreateKMatrixStressbalanceSIA(void);
+		ElementMatrix* CreateKMatrixStressbalanceFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceFSViscous(void);
+		ElementMatrix* CreateKMatrixStressbalanceFSFriction(void);
 		ElementVector* CreatePVectorStressbalanceSSA(void);
 		ElementVector* CreatePVectorStressbalanceSSADrivingStress(void);
 		ElementVector* CreatePVectorStressbalanceSSAFront(void);
 		ElementVector* CreatePVectorStressbalanceSIA(void);
+		ElementVector* CreatePVectorStressbalanceFS(void);
+		ElementVector* CreatePVectorStressbalanceFSFront(void);
+		ElementVector* CreatePVectorStressbalanceFSViscous(void);
+		void           PVectorGLSstabilization(ElementVector* pe);
+		ElementVector* CreatePVectorStressbalanceFSShelf(void);
 		ElementMatrix* CreateJacobianStressbalanceSSA(void);
-		void	  GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution);
-		void	  GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solution);
-		void	  InputUpdateFromSolutionStressbalanceHoriz( IssmDouble* solution);
-		void	  InputUpdateFromSolutionStressbalanceSIA( IssmDouble* solution);
+		void	         GetSolutionFromInputsStressbalanceFS(Vector<IssmDouble>* solution);
+		void	         GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution);
+		void	         GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solution);
+		IssmDouble     GetYcoord(GaussTria* gauss);
+		void	         InputUpdateFromSolutionStressbalanceHoriz( IssmDouble* solution);
+		void	         InputUpdateFromSolutionStressbalanceFS( IssmDouble* solution);
+		void	         InputUpdateFromSolutionStressbalanceSIA( IssmDouble* solution);
 		#endif
 
@@ -250,8 +277,10 @@
 		#endif
 
+		void UpdateConstraintsExtrudeFromBase(void);
+		void UpdateConstraintsExtrudeFromTop(void);
 		#ifdef _HAVE_THERMAL_
-		void UpdateThermalBasalConstraints(void){_error_("not implemented yet");};
+		void UpdateBasalConstraintsEnthalpy(void){_error_("not implemented yet");};
 		void ComputeBasalMeltingrate(void){_error_("not implemented yet");};
-	        void DrainWaterfraction(void){_error_("not implemented yet");};
+		void DrainWaterfraction(void){_error_("not implemented yet");};
 		#endif
 
@@ -277,6 +306,14 @@
 		bool    AnyActive(void);
 		#endif
-		#ifdef _HAVE_BALANCED_
-		#endif
+
+		#ifdef _HAVE_DAMAGE_
+		ElementMatrix* CreateKMatrixDamageEvolution(void);
+		ElementMatrix* CreateKMatrixDamageEvolution_CG(void);
+		ElementVector* CreatePVectorDamageEvolution(void);
+		ElementVector* CreatePVectorDamageEvolution_CG(void);
+		void           DamageEvolutionF(IssmDouble* flist);
+		void	         InputUpdateFromSolutionDamageEvolution(IssmDouble* solution);
+		#endif
+
 
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 16560)
@@ -43,6 +43,4 @@
 /*FUNCTION TriaRef::SetElementType{{{*/
 void TriaRef::SetElementType(int type,int type_counter){
-
-	_assert_(type==P1Enum || type==P1DGEnum || type==P1bubbleEnum || type==P1bubblecondensedEnum || type==P2Enum);
 
 	/*initialize element type*/
@@ -59,5 +57,5 @@
 	 *       Bi=[ dN/dx ]
 	 *          [ dN/dy ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -89,5 +87,5 @@
 	 *          [   0           dN/dy  ]
 	 *          [ 1/2*dN/dy  1/2*dN/dx ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -124,5 +122,5 @@
 	 *          [       0       dN/dy   ]
 	 *          [  1/2*dN/dy  1/2*dN/dx ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -202,4 +200,135 @@
 }
 /*}}}*/
+/*FUNCTION TriaRef::GetBExtrusion{{{*/
+void TriaRef::GetBExtrusion(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[1*numnodes+i];  
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBFS {{{*/
+void TriaRef::GetBFS(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
+	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
+	 * For node i, Bvi can be expressed in the actual coordinate system
+	 * by: 	   Bvi=[ dphi/dx          0        ]
+	 *					 [   0           dphi/dy     ]
+	 *					 [ 1/2*dphi/dy    1/2*dphi/dx]
+	 *					 [   0             0         ]
+	 *					 [ dphi/dx         dphi/dy   ]
+	 *
+	 * by: 	  Bpi=[  0    ]
+	 *					[  0    ]
+	 *					[  0    ]
+	 *					[ phi_p ]
+	 *					[  0    ]
+	 *	where phi is the finiteelement function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(2*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	GetNodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	GetNodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<vnumnodes;i++){
+		B[(2*vnumnodes+pnumnodes)*0+2*i+0] = vdbasis[0*vnumnodes+i];
+		B[(2*vnumnodes+pnumnodes)*0+2*i+1] = 0.;
+		B[(2*vnumnodes+pnumnodes)*1+2*i+0] = 0.;
+		B[(2*vnumnodes+pnumnodes)*1+2*i+1] = vdbasis[1*vnumnodes+i];
+		B[(2*vnumnodes+pnumnodes)*2+2*i+0] = .5*vdbasis[1*vnumnodes+i];
+		B[(2*vnumnodes+pnumnodes)*2+2*i+1] = .5*vdbasis[0*vnumnodes+i];
+		B[(2*vnumnodes+pnumnodes)*3+2*i+0] = 0.;
+		B[(2*vnumnodes+pnumnodes)*3+2*i+1] = 0.;
+		B[(2*vnumnodes+pnumnodes)*4+2*i+0] = vdbasis[0*vnumnodes+i];
+		B[(2*vnumnodes+pnumnodes)*4+2*i+1] = vdbasis[1*vnumnodes+i];
+	}
+	for(int i=0;i<pnumnodes;i++){
+		B[(2*vnumnodes+pnumnodes)*0+(2*vnumnodes)+i] = 0.;
+		B[(2*vnumnodes+pnumnodes)*1+(2*vnumnodes)+i] = 0.;
+		B[(2*vnumnodes+pnumnodes)*2+(2*vnumnodes)+i] = 0.;
+		B[(2*vnumnodes+pnumnodes)*3+(2*vnumnodes)+i] = pbasis[i];
+		B[(2*vnumnodes+pnumnodes)*4+(2*vnumnodes)+i] = 0.;
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimeFS {{{*/
+void TriaRef::GetBprimeFS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussTria* gauss){
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx     0     ]
+	 *					 [     0      dphi/dy ]
+	 *					 [  dphi/dy   dphi/dx ]
+	 *					 [  dphi/dx   dphi/dy ]
+	 *					 [     0      0       ]
+	 *
+	 * by: 	  Bpi=[  0  ]
+	 *					[  0  ]
+	 *					[  0  ]
+	 *					[  0  ]
+	 *					[ phi ]
+	 *	where phi is the finiteelement function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(2*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	GetNodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	GetNodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B_prime: */
+	for(int i=0;i<vnumnodes;i++){
+		B_prime[(2*vnumnodes+pnumnodes)*0+2*i+0] = vdbasis[0*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*0+2*i+1] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*1+2*i+0] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*1+2*i+1] = vdbasis[1*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*2+2*i+0] = vdbasis[1*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*2+2*i+1] = vdbasis[0*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*3+2*i+0] = vdbasis[0*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*3+2*i+1] = vdbasis[1*vnumnodes+i];
+		B_prime[(2*vnumnodes+pnumnodes)*4+2*i+0] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*4+2*i+1] = 0.;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		B_prime[(2*vnumnodes+pnumnodes)*0+(2*vnumnodes)+i] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*1+(2*vnumnodes)+i] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*2+(2*vnumnodes)+i] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*3+(2*vnumnodes)+i] = 0.;
+		B_prime[(2*vnumnodes+pnumnodes)*4+(2*vnumnodes)+i] = pbasis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}
+/*}}}*/
 /*FUNCTION TriaRef::GetBMasstransport{{{*/
 void TriaRef::GetBMasstransport(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
@@ -209,5 +338,5 @@
 	 *       Bi=[ N ]
 	 *          [ N ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
@@ -240,5 +369,5 @@
 	 *                [   dN/dx  2*dN/dy ]
 	 *                [   dN/dy    dN/dx ]
-	 * where hNis the interpolation function for node i.
+	 * where hNis the finiteelement function for node i.
 	 *
 	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -275,5 +404,5 @@
 	 *               [  dN/dy  dN/dx ]
 	 N               [  dN/dx  dN/dy ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -310,5 +439,5 @@
 	 *       Bi_prime=[ dN/dx ]
 	 *                [ dN/dy ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
@@ -339,5 +468,5 @@
 	 *                 Bi=[ N   0 ]
 	 *                    [ 0   N ]
-	 * where N is the interpolation function for node i.
+	 * where N is the finiteelement function for node i.
 	 *
 	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
@@ -363,4 +492,37 @@
 }
 /*}}}*/
+/*FUNCTION TriaRef::GetLFS{{{*/
+void TriaRef::GetLFS(IssmDouble* LFS, GaussTria* 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 ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumdof   = pnumnodes;
+	int vnumdof   = vnumnodes*NDOF2;
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
+	GetNodalFunctionsVelocity(vbasis,gauss);
+
+	/*Build LFS: */
+	for(int i=0;i<vnumnodes;i++){
+		LFS[2*i+0] = vbasis[i];
+		LFS[2*i+1] = 0.;
+	}
+
+	for(int i=0;i<pnumnodes;i++){
+		LFS[i+vnumdof+0] = 0.;
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(vbasis);
+}
+/*}}}*/
 /*FUNCTION TriaRef::GetJacobian{{{*/
 void TriaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTria* gauss){
@@ -425,11 +587,20 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetNodalFunctions{{{*/
+/*FUNCTION TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss){{{*/
 void TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss){
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
 
 	_assert_(basis);
-
-	switch(this->element_type){
+	GetNodalFunctions(basis,gauss,this->element_type);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss,int finiteelement){{{*/
+void TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss,int finiteelement){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	switch(finiteelement){
 		case P1Enum: case P1DGEnum:
 			basis[0]=gauss->coord1;
@@ -460,4 +631,74 @@
 }
 /*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsVelocity{{{*/
+void TriaRef::GetNodalFunctionsVelocity(IssmDouble* basis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P2Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsPressure{{{*/
+void TriaRef::GetNodalFunctionsPressure(IssmDouble* basis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
 /*FUNCTION TriaRef::GetSegmentNodalFunctions{{{*/
 void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,GaussTria* gauss,int index1,int index2){
@@ -500,6 +741,13 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetNodalFunctionsDerivatives{{{*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss){{{*/
 void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss){
+
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss,int finiteelement){{{*/
+void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss,int finiteelement){
 
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
@@ -508,9 +756,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions derivatives in reference triangle*/
 	IssmDouble* dbasis_ref=xNew<IssmDouble>(2*numnodes);
-	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss); 
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement); 
 
 	/*Get Jacobian invert: */
@@ -531,12 +779,87 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference{{{*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesPressure{{{*/
+void TriaRef::GetNodalFunctionsDerivativesPressure(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss){
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesVelocity{{{*/
+void TriaRef::GetNodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss){
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P2Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss){{{*/
 void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss){
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
 	 * natural coordinate system) at the gaussian point. */
 
+	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss,int finiteelement){{{*/
+void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss,int finiteelement){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
 	_assert_(dbasis && gauss);
 
-	switch(this->element_type){
+	switch(finiteelement){
 		case P1Enum: case P1DGEnum:
 			/*Nodal function 1*/
@@ -623,6 +946,12 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetInputValue{{{*/
+/*FUNCTION TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss){{{*/
 void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss){
+
+	GetInputValue(p,plist,gauss,this->element_type);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss,int finiteelement){{{*/
+void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss,int finiteelement){
 
 	/*Output*/
@@ -630,9 +959,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions*/
 	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis, gauss);
+	GetNodalFunctions(basis, gauss,finiteelement);
 
 	/*Calculate parameter for this Gauss point*/
@@ -644,8 +973,14 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::NumberofNodes{{{*/
+/*FUNCTION TriaRef::NumberofNodes(){{{*/
 int TriaRef::NumberofNodes(void){
 
-	switch(this->element_type){
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+/*FUNCTION TriaRef::NumberofNodes(int finiteelement){{{*/
+int TriaRef::NumberofNodes(int finiteelement){
+
+	switch(finiteelement){
 		case P1Enum:                return NUMNODESP1;
 		case P1DGEnum:              return NUMNODESP1;
@@ -653,4 +988,9 @@
 		case P1bubblecondensedEnum: return NUMNODESP1b;
 		case P2Enum:                return NUMNODESP2;
+		case P1P1Enum:              return NUMNODESP1*2;
+		case P1P1GLSEnum:           return NUMNODESP1*2;
+		case MINIcondensedEnum:     return NUMNODESP1b+NUMNODESP1;
+		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
+		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
 		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
 	}
@@ -659,2 +999,122 @@
 }
 /*}}}*/
+/*FUNCTION TriaRef::NumberofNodesPressure{{{*/
+int TriaRef::NumberofNodesPressure(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return NUMNODESP1;
+		case P1P1GLSEnum:       return NUMNODESP1;
+		case MINIcondensedEnum: return NUMNODESP1;
+		case MINIEnum:          return NUMNODESP1;
+		case TaylorHoodEnum:    return NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION TriaRef::NumberofNodesVelocity{{{*/
+int TriaRef::NumberofNodesVelocity(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return NUMNODESP1;
+		case P1P1GLSEnum:       return NUMNODESP1;
+		case MINIcondensedEnum: return NUMNODESP1b;
+		case MINIEnum:          return NUMNODESP1b;
+		case TaylorHoodEnum:    return NUMNODESP2;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION TriaRef::VelocityInterpolation{{{*/
+int TriaRef::VelocityInterpolation(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1bubbleEnum;
+		case MINIEnum:          return P1bubbleEnum;
+		case TaylorHoodEnum:    return P2Enum;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION TriaRef::PressureInterpolation{{{*/
+int TriaRef::PressureInterpolation(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1Enum;
+		case MINIEnum:          return P1Enum;
+		case TaylorHoodEnum:    return P1Enum;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION TriaRef::NodeOnEdgeIndices{{{*/
+void TriaRef::NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement){
+
+	/*Output*/
+	int  numindices;
+	int* indices = NULL;
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum: case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 2;
+			indices    = xNew<int>(numindices);
+			switch(index){
+				case 0:
+					indices[0] = 1;
+					indices[1] = 2;
+					break;
+				case 1:
+					indices[0] = 2;
+					indices[1] = 0;
+					break;
+				case 2:
+					indices[0] = 0;
+					indices[1] = 1;
+					break;
+				default:
+					_error_("Edge index provided ("<<index<<") is not between 0 and 2");
+			}
+			break;
+		case P2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			switch(index){
+				case 0:
+					indices[0] = 1;
+					indices[1] = 2;
+					indices[2] = 3;
+					break;
+				case 1:
+					indices[0] = 2;
+					indices[1] = 0;
+					indices[2] = 4;
+					break;
+				case 2:
+					indices[0] = 0;
+					indices[1] = 1;
+					indices[2] = 5;
+					break;
+				default:
+					_error_("Edge index provided ("<<index<<") is not between 0 and 2");
+			}
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 16560)
@@ -23,6 +23,9 @@
 
 		/*Numerics*/
+		void GetBExtrusion(IssmDouble* B_prime, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBFS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetBSSA(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetBSSAFS(IssmDouble* B , IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBprimeFS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetBprimeSSA(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetBprimeSSAFS(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
@@ -35,14 +38,29 @@
 		void GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
 		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetLFS(IssmDouble* LFS, GaussTria* gauss);
 		void GetNodalFunctions(IssmDouble* basis,GaussTria* gauss);
+		void GetNodalFunctions(IssmDouble* basis,GaussTria* gauss,int finiteelement);
+		void GetNodalFunctionsVelocity(IssmDouble* basis, GaussTria* gauss);
+		void GetNodalFunctionsPressure(IssmDouble* basis, GaussTria* gauss);
 		void GetSegmentNodalFunctions(IssmDouble* basis,GaussTria* gauss, int index1,int index2);
 		void GetSegmentBFlux(IssmDouble* B,GaussTria* gauss, int index1,int index2);
 		void GetSegmentBprimeFlux(IssmDouble* Bprime,GaussTria* gauss, int index1,int index2);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,GaussTria* gauss);
+		void GetNodalFunctionsDerivativesPressure(IssmDouble* dbasis,IssmDouble* xyz_list,GaussTria* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss,int finiteelement);
 		void GetInputValue(IssmDouble* pp, IssmDouble* plist, GaussTria* gauss);
+		void GetInputValue(IssmDouble* pp, IssmDouble* plist, GaussTria* gauss,int finiteelement);
 		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss);
 
+		void NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement);
 		int  NumberofNodes(void);
+		int  NumberofNodes(int finiteelement);
+		int  NumberofNodesVelocity(void);
+		int  NumberofNodesPressure(void);
+		int  VelocityInterpolation(void);
+		int  PressureInterpolation(void);
 };
 #endif
Index: /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 16559)
+++ /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 16560)
@@ -23,11 +23,9 @@
 	public: 
 
-		virtual        ~ExternalResult(){};
-		/*Virtual functions:{{{*/
-		virtual int   InstanceEnum()=0;
-		virtual void  WriteData(FILE* fid,bool io_gather)=0;
-		virtual void  GetResultName(char**)=0;
-		virtual int   GetStep(void)=0;
-		/*}}}*/
+		virtual         ~ExternalResult(){};
+		virtual void   WriteData(FILE* fid,bool io_gather)=0;
+		virtual char*  GetResultName(void)=0;
+		virtual int    GetStep(void)=0;
+		virtual double GetValue(void)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 16559)
+++ /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 16560)
@@ -22,10 +22,10 @@
 
 	private: 
-		int id;
-		int enum_type;
+		int        id;
+		char*      result_name;
 		ResultType value;
-		int M;
-		int N;
-		int step;
+		int        M;
+		int        N;
+		int        step;
 		IssmDouble time;
 
@@ -33,22 +33,18 @@
 		/*Diverse: must be in front, as it is used in what follows*/
 		void GenericEcho(void){/*{{{*/
-			_printf_("   id: " << this->id << "\n");
-			_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
-			_printf_("   step: " << this->step << "\n");
-			_printf_("   time: " << this->time << "\n");
+			_printf_("   id          : " << this->id << "\n");
+			_printf_("   result_name : " << this->result_name<< "\n");
+			_printf_("   step        : " << this->step << "\n");
+			_printf_("   time        : " << this->time << "\n");
 		}
 		/*}}}*/
 		void GenericWriteData(FILE* fid){/*{{{*/ 
 
-			int     length;
 			IssmPDouble  passiveDouble;
-			char*   name = NULL;
-
-			/*First write enum: */
-			EnumToStringx(&name,this->enum_type);
-			length=(strlen(name)+1)*sizeof(char);
+
+			/*First write name: */
+			int length=(strlen(this->result_name)+1)*sizeof(char);
 			fwrite(&length,sizeof(int),1,fid);
-			fwrite(name,length,1,fid);
-			xDelete<char>(name);
+			fwrite(this->result_name,length,1,fid);
 
 			/*Now write time and step: */
@@ -60,24 +56,44 @@
 		/*GenericExternalResult constructors and  destructors*/
 		GenericExternalResult(){ /*{{{*/
-			id  = 0;
-			enum_type = NoneEnum;
-			M=0;
-			N=0;
-			step=0;
-			time=0;
+			id          = 0;
+			result_name = NULL;
+			M           = 0;
+			N           = 0;
+			step        = 0;
+			time        = 0;
 		} /*}}}*/
 		GenericExternalResult(int in_id, int in_enum_type,ResultType in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+			id          = 0;
+			result_name = NULL;
+			M           = 0;
+			N           = 0;
+			step        = 0;
+			time        = 0;
 			_error_("template GenericExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_N,int in_step,IssmDouble in_time) not implemented for this ResultType\n");
 		}
 /*}}}*/
 		GenericExternalResult(int in_id, int in_enum_type,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
-			id=in_id;
-			enum_type=in_enum_type;
-			value=in_value;
-			step=in_step;
-			time=in_time;
+			id        = in_id;
+			value     = in_value;
+			step      = in_step;
+			time      = in_time;
+
+			/*Convert enum to name*/
+			EnumToStringx(&this->result_name,in_enum_type);
+		}
+		/*}}}*/
+		GenericExternalResult(int in_id,const char* in_result_name,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
+			id        = in_id;
+			value     = in_value;
+			step      = in_step;
+			time      = in_time;
+
+			/*Copy name*/
+			this->result_name = xNew<char>(strlen(in_result_name)+1);
+			xMemCpy<char>(this->result_name,in_result_name,strlen(in_result_name)+1);
 		}
 		/*}}}*/
 		~GenericExternalResult(){ /*{{{*/
+			xDelete<char>(result_name);
 		} /*}}}*/
 
@@ -98,9 +114,9 @@
 		} /*}}}*/
 		Object* copy(void) { /*{{{*/
-			return new GenericExternalResult<ResultType>(this->id,this->enum_type,this->value,this->step,this->time);
+			return new GenericExternalResult<ResultType>(this->id,this->result_name,this->value,this->step,this->time);
 		} /*}}}*/
 
 		/*GenericExternalResult management: */
-void WriteData(FILE* fid,bool io_gather){ /*{{{*/
+void  WriteData(FILE* fid,bool io_gather){ /*{{{*/
 
 	int     my_rank;
@@ -129,12 +145,16 @@
 
 } /*}}}*/
-void GetResultName(char** pname){ /*{{{*/
-	EnumToStringx(pname,this->enum_type);
-} /*}}}*/
-int GetStep(void){ /*{{{*/
+char* GetResultName(void){ /*{{{*/
+		char* name = xNew<char>(strlen(this->result_name)+1);
+		xMemCpy<char>(name,this->result_name,strlen(this->result_name)+1);
+		return name;
+} /*}}}*/
+int   GetStep(void){ /*{{{*/
 	return this->step;
 } /*}}}*/
-int InstanceEnum(void){ /*{{{*/
-	return this->enum_type;
+IssmPDouble GetValue(void){ /*{{{*/
+	/*Only supported by IssmPDouble result, error out by default*/
+	_error_("not supported for this type of result");
+	return 0.;
 } /*}}}*/
 };
@@ -175,17 +195,23 @@
 	return DoubleExternalResultEnum;
 } /*}}}*/
+template <> inline double GenericExternalResult<double>::GetValue(void){ /*{{{*/
+	return value;
+} /*}}}*/
 
 /*Specific instantiations for char*: */
 template <> inline GenericExternalResult<char*>::GenericExternalResult(int in_id, int in_enum_type,char* in_value,int in_step, IssmDouble in_time){ /*{{{*/
 
-	id=in_id;
-	enum_type=in_enum_type;
-	value=xNew<char>(strlen(in_value)+1);
+	id = in_id;
+	value = xNew<char>(strlen(in_value)+1);
 	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
-	step=in_step;
-	time=in_time;
+	step  = in_step;
+	time  = in_time;
+
+	/*Convert enum to name*/
+	EnumToStringx(&this->result_name,in_enum_type);
 
 } /*}}}*/
 template <> inline GenericExternalResult<char*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(result_name);
 	xDelete<char>(value);
 } /*}}}*/
@@ -228,11 +254,12 @@
 template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
 
-	id=in_id;
-	enum_type=in_enum_type;
-	M=in_M;
-	N=in_N;
-
-	step=in_step;
-	time=in_time;
+	id = in_id;
+	M  = in_M;
+	N  = in_N;
+
+	EnumToStringx(&this->result_name,in_enum_type);
+
+	step = in_step;
+	time = in_time;
 
 	/*Copy result in values*/
@@ -248,4 +275,5 @@
 } /*}}}*/
 template <> inline GenericExternalResult<IssmPDouble*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(result_name);
 	xDelete<IssmPDouble>(value);
 } /*}}}*/
@@ -275,10 +303,9 @@
 } /*}}}*/
 template <> inline Object* GenericExternalResult<IssmPDouble*>::copy(void){ /*{{{*/
-	return new GenericExternalResult<IssmPDouble*>(this->id,this->enum_type,this->value,this->M,this->N,this->step,this->time);
+	return new GenericExternalResult<IssmPDouble*>(this->id,StringToEnumx(this->result_name),this->value,this->M,this->N,this->step,this->time);
 } /*}}}*/
 template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
 
 	int     my_rank;
-	int     length;
 	int     type;
 	int     rows,cols;
@@ -295,9 +322,7 @@
 
 	/*First write enum: */
-	EnumToStringx(&name,this->enum_type);
-	length=(strlen(name)+1)*sizeof(char);
+	int length=(strlen(this->result_name)+1)*sizeof(char);
 	fwrite(&length,sizeof(int),1,fid);
-	fwrite(name,length,1,fid);
-	xDelete<char>(name);
+	fwrite(this->result_name,length,1,fid);
 
 	/*Now write time and step: */
@@ -321,3 +346,82 @@
 } /*}}}*/
 
+/*Specifics instantiations for Vector*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::GenericExternalResult(int in_id, int in_enum_type,Vector<IssmPDouble>* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+	_error_("instanciation not correct");
+}
+/*}}}*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::GenericExternalResult(int in_id, int in_enum_type,Vector<IssmPDouble>* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+	id = in_id;
+	M  = 0;
+	N  = 0;
+
+	/*Convert enum to name*/
+	EnumToStringx(&this->result_name,in_enum_type);
+
+	step = in_step;
+	time = in_time;
+
+	value = in_value;
+} /*}}}*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(this->result_name);
+	delete value;
+} /*}}}*/
+template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::Echo(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<Vector<IssmPDouble>*>:\n");
+	this->GenericEcho();
+	this->value->Echo();
+
+} /*}}}*/
+template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::DeepEcho(void){ /*{{{*/
+
+	this->Echo();
+
+} /*}}}*/
+template <> inline Object* GenericExternalResult<Vector<IssmPDouble>*>::copy(void){ /*{{{*/
+	return new GenericExternalResult<Vector<IssmPDouble>*>(this->id,StringToEnumx(this->result_name),this->value,this->step,this->time);
+} /*}}}*/
+template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	char *name   = NULL;
+	int   length,rows,cols=1;
+
+	if(!io_gather){
+		_error_("not supported yet");
+	}
+
+	/*Serialize vector*/
+	IssmPDouble* serialvalues = this->value->ToMPISerial();
+	this->value->GetSize(&rows);
+
+	if(IssmComm::GetRank()==0){
+		/*First write name: */
+		length=(strlen(this->result_name)+1)*sizeof(char);
+		fwrite(&length,sizeof(int),1,fid);
+		fwrite(this->result_name,length,1,fid);
+
+		/*Now write time and step: */
+		IssmPDouble passiveDouble=reCast<IssmPDouble>(time);
+		fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+		fwrite(&step,sizeof(int),1,fid);
+
+		/*writing a IssmDouble array, type is 3:*/
+		int type=3;
+		fwrite(&type,sizeof(int),1,fid);
+		fwrite(&rows,sizeof(int),1,fid);
+		fwrite(&cols,sizeof(int),1,fid);
+		fwrite(serialvalues,cols*rows*sizeof(IssmPDouble),1,fid);
+	}
+
+	/*Clean up*/
+	xDelete<IssmPDouble>(serialvalues);
+
+}
+/*}}}*/
+template <> inline int GenericExternalResult<Vector<IssmPDouble>*>::ObjectEnum(void){ /*{{{*/
+	return NoneEnum;
+	/*???? FIXME*/
+} /*}}}*/
+
 #endif  /* _EXTERNAL_RESULTOBJECT_H */
Index: /issm/trunk/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 16560)
@@ -15,5 +15,4 @@
 #include "../../shared/shared.h"
 #include "../Params/Parameters.h"
-#include "../ElementResults/ElementResult.h"
 
 using namespace std;
@@ -37,7 +36,6 @@
 void Results::Write(Parameters* parameters){
 
-	int         i;
-	FILE       *fid          = NULL;
-	bool        io_gather=true;
+	FILE       *fid  = NULL;
+	bool        io_gather;
 
 	/*Recover file descriptor: */
@@ -45,8 +43,6 @@
 	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
 
-	for(i=0;i<this->Size();i++){
+	for(int i=0;i<this->Size();i++){
 		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
-
-		/*write result to disk: */
 		result->WriteData(fid,io_gather);
 	}
@@ -54,25 +50,29 @@
 }
 /*}}}*/
-/*FUNCTION Results::Write{{{*/
-int Results::AddResult(ElementResult* in_result){
+/*FUNCTION Results::AddResult(ExternalResult* in_result){{{*/
+int Results::AddResult(ExternalResult* in_result){
 
 	/*First, go through dataset of inputs and check whether any input 
 	 * with the same name is already in. If so, erase the corresponding 
 	 * object before adding this new one: */
-	vector<Object*>::iterator object;
-	ElementResult* result=NULL;
 
 	/*In debugging mode, check that the input is not a NULL pointer*/
 	_assert_(in_result);
 
-	for(object=objects.begin() ; object<objects.end(); object++){
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
 
-		result=dynamic_cast<ElementResult*>(*object);
+		if(result->GetStep()==in_result->GetStep()){
+			char*    result_name =    result->GetResultName();
+			char* in_result_name = in_result->GetResultName();
+			if(strcmp(in_result_name,result_name)==0){
 
-		if(result->InstanceEnum()==in_result->InstanceEnum()){
-			if(result->GetStep()==in_result->GetStep()){
 				this->DeleteObject(result);
+				xDelete<char>(result_name);
+				xDelete<char>(in_result_name);
 				break;
 			}
+			xDelete<char>(result_name);
+			xDelete<char>(in_result_name);
 		}
 	}
@@ -82,2 +82,19 @@
 }
 /*}}}*/
+/*FUNCTION Results::DeleteResult(ExternalResult* in_result){{{*/
+int Results::DeleteResult(int result_enum,int result_step){
+
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+
+		if(result->GetStep()==result_step){
+			if(strcmp(result->GetResultName(),EnumToStringx(result_enum))==0){
+				this->DeleteObject(result);
+				break;
+			}
+		}
+	}
+
+	return 1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/ExternalResults/Results.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 16559)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 16560)
@@ -6,5 +6,5 @@
 /*forward declarations */
 class Parameters;
-class ElementResult;
+class ExternalResult;
 
 /*!\brief Declaration of Results class.
@@ -21,5 +21,6 @@
 
 		/*Mehthos*/
-		int AddResult(ElementResult* result);
+		int AddResult(ExternalResult* result);
+		int DeleteResult(int result_enum,int result_step);
 		void Write(Parameters* parameters);
 };
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 16560)
@@ -10,7 +10,8 @@
 
 #include <stdio.h>
-#include "../analyses/analyses.h"
+#include "../cores/cores.h"
 #include "../shared/io/io.h"
 #include "./classes.h"
+#include "./modules/modules.h"
 #include "../shared/Enum/Enum.h"
 
@@ -190,4 +191,7 @@
 	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
 
+	/*Open toolkits file: */
+	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
+
 	/*Initialize internal data: */
 	this->nummodels        = nummodels;
@@ -203,5 +207,5 @@
 
 	/*create datasets for all analyses*/
-	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,rootpath,this->solution_type,nummodels,analyses);
+	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,toolkitsoptionsfid,rootpath,this->solution_type,nummodels,analyses);
 
 	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
@@ -227,6 +231,7 @@
 	}
 
-	/*Close input file descriptors: */
+	/*Close input file and toolkits file descriptors: */
 	if(my_rank==0) pfclose(IOMODEL,inputfilename);
+	pfclose(toolkitsoptionsfid,toolkitsfilename);
 
 	/*Open output file once for all and add output file name and file descriptor to parameters*/
@@ -238,9 +243,5 @@
 	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
 
-	/*Now, deal with toolkits options, which need to be put into the parameters dataset: */
-	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
-	ParseToolkitsOptionsx(this->parameters,toolkitsoptionsfid);
-	pfclose(toolkitsoptionsfid,toolkitsfilename);
-}
+	}
 /*}}}*/
 /*FUNCTION FemModel::OutputResults {{{*/
@@ -368,31 +369,38 @@
 int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
 
-	Vector<IssmDouble> *vz        = NULL;
-	IssmDouble         *thickness = NULL;
-	IssmDouble         *bed       = NULL;
+	IssmDouble         *surface = NULL;
+	IssmDouble         *bed     = NULL;
 
 	/*get vertex vectors for bed and thickness: */
-	GetVectorFromInputsx(&thickness,this, ThicknessEnum,VertexEnum);
-	GetVectorFromInputsx(&bed      ,this, BedEnum,      VertexEnum);
+	GetVectorFromInputsx(&surface  ,this, SurfaceEnum,VertexEnum);
+	GetVectorFromInputsx(&bed      ,this, BedEnum,    VertexEnum);
 
 	/*Allocate vector*/
-	vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	Vector<IssmDouble> *vx=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	Vector<IssmDouble> *vy=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	Vector<IssmDouble> *vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
 
 	/*Update verices new geometry: */
 	for(int i=0;i<vertices->Size();i++){
 		Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
-		vertex->UpdatePosition(vz,parameters,thickness,bed);
+		vertex->UpdatePosition(vx,vy,vz,parameters,surface,bed);
 	}
 
 	/*Assemble mesh velocity*/
+	vx->Assemble();
+	vy->Assemble();
 	vz->Assemble();
 
 	/*Update element inputs*/
+	InputUpdateFromVectorx(this,vx,VxMeshEnum,VertexPIdEnum);
+	InputUpdateFromVectorx(this,vy,VyMeshEnum,VertexPIdEnum);
 	InputUpdateFromVectorx(this,vz,VzMeshEnum,VertexPIdEnum);
 
 	/*Free ressources:*/
+	delete vx;
+	delete vy;
 	delete vz;
 	xDelete<IssmDouble>(bed);
-	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(surface);
 	return 1;
 }
@@ -400,5 +408,4 @@
 void FemModel::UpdateConstraintsx(void){ /*{{{*/
 
-	Element   *element = NULL;
 	IssmDouble time;
 	int        analysis_type;
@@ -419,47 +426,48 @@
 }
 /*}}}*/
-void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor,int weight_index){/*{{{*/
+void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor){/*{{{*/
 
 	int response_descriptor_enum=StringToEnumx(response_descriptor);
-	this->Responsex(responses, response_descriptor_enum,weight_index);
-
-}
-/*}}}*/
-void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum,int weight_index){/*{{{*/
+	this->Responsex(responses, response_descriptor_enum);
+
+}
+/*}}}*/
+void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum){/*{{{*/
 
 	switch (response_descriptor_enum){
 
 		#ifdef _HAVE_RESPONSES_
-		case IceVolumeEnum:              this->IceVolumex(responses); break;
-		case MinVelEnum:                 this->MinVelx(responses); break;
-		case MaxVelEnum:                 this->MaxVelx(                  responses); break;
-		case MinVxEnum:                  this->MinVxx(responses); break;
-		case MaxVxEnum:                  this->MaxVxx(                   responses); break;
-		case MaxAbsVxEnum:               this->MaxAbsVxx(                responses); break;
-		case MinVyEnum:                  this->MinVyx(responses); break;
-		case MaxVyEnum:                  this->MaxVyx(                   responses); break;
-		case MaxAbsVyEnum:               this->MaxAbsVyx(                responses); break;
-		case MinVzEnum:                  this->MinVzx(responses); break;
-		case MaxVzEnum:                  this->MaxVzx(                   responses); break;
-		case MaxAbsVzEnum:               this->MaxAbsVzx(                responses); break;
-		case MassFluxEnum:               this->MassFluxx(         responses); break;
+		case IceVolumeEnum:                this->IceVolumex(responses); break;
+		case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(responses); break;
+		case MinVelEnum:                   this->MinVelx(responses); break;
+		case MaxVelEnum:                   this->MaxVelx(                  responses); break;
+		case MinVxEnum:                    this->MinVxx(responses); break;
+		case MaxVxEnum:                    this->MaxVxx(                   responses); break;
+		case MaxAbsVxEnum:                 this->MaxAbsVxx(                responses); break;
+		case MinVyEnum:                    this->MinVyx(responses); break;
+		case MaxVyEnum:                    this->MaxVyx(                   responses); break;
+		case MaxAbsVyEnum:                 this->MaxAbsVyx(                responses); break;
+		case MinVzEnum:                    this->MinVzx(responses); break;
+		case MaxVzEnum:                    this->MaxVzx(                   responses); break;
+		case MaxAbsVzEnum:                 this->MaxAbsVzx(                responses); break;
+		case MassFluxEnum:                 this->MassFluxx(         responses); break;
 		#ifdef _HAVE_CONTROL_
-		case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx(responses,this,weight_index); break;
-		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses,weight_index); break;
-		case ThicknessAlongGradientEnum: ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case ThicknessAcrossGradientEnum:ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case BalancethicknessMisfitEnum:BalancethicknessMisfitx(responses,weight_index); break;
+		case SurfaceAbsVelMisfitEnum:      SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceRelVelMisfitEnum:      SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVelMisfitEnum:      SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVxVyMisfitEnum:     SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceAverageVelMisfitEnum:  SurfaceAverageVelMisfitx(responses,this); break;
+		case ThicknessAbsMisfitEnum:       ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAbsGradientEnum:     this->ThicknessAbsGradientx(responses); break;
+		case ThicknessAlongGradientEnum:   ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAcrossGradientEnum:  ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case RheologyBbarAbsGradientEnum:  RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case BalancethicknessMisfitEnum:   BalancethicknessMisfitx(responses); break;
 		#endif
-		case TotalSmbEnum:					this->TotalSmbx(responses); break;
-		case MaterialsRheologyBbarEnum: this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
-		case VelEnum:                   this->ElementResponsex(responses,VelEnum); break;
-		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
+		case TotalSmbEnum:					  this->TotalSmbx(responses); break;
+		case MaterialsRheologyBbarEnum:    this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
+		case VelEnum:                      this->ElementResponsex(responses,VelEnum); break;
+		case FrictionCoefficientEnum:      NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
 		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break;
 		#else
@@ -470,11 +478,16 @@
 }
 /*}}}*/
-void FemModel::RequestedOutputsx(int* requested_outputs, int numoutputs){/*{{{*/
-
-	int      output_enum;
-	int      step;
-	IssmDouble   time;
-	IssmDouble   output_value;
-	Element *element      = NULL;
+void FemModel::RequestedOutputsx(Results **presults,char** requested_outputs, int numoutputs){/*{{{*/
+
+	/*Intermediaries*/
+	bool        isvec;
+	int         step,output_enum;
+	IssmDouble  time;
+	IssmDouble  double_result;
+	const char *output_string = NULL;
+
+	/*recover results*/
+	Results* results = *presults;
+	if(!results) results = new Results();
 
 	/*Get time and step*/
@@ -482,33 +495,115 @@
 	parameters->FindParam(&time,TimeEnum);
 
-	/*retrieve Inputs*/
-	if(numoutputs){
-		for(int i=0;i<numoutputs;i++){
-			output_enum=requested_outputs[i];
-
+	/*Go through all requested output*/
+	for(int i=0;i<numoutputs;i++){
+
+		output_string = requested_outputs[i];
+		output_enum   = StringToEnumx(output_string,false);
+		isvec         = false;
+
+		/*If string is not an enum, it is defined in output definitions*/
+		if(output_enum<0){
+			double_result = OutputDefinitionsResponsex(this,output_string);
+		}
+		else{
 			switch(output_enum){
 
-				case IceVolumeEnum:
-					Responsex(&output_value,"IceVolume",0);
-					results->AddObject(new GenericExternalResult<double>(results->Size()+1,IceVolumeEnum,reCast<IssmPDouble>(output_value),step,time));
+				#ifdef _HAVE_RESPONSES_
+				/*Scalar output*/
+				case IceVolumeEnum:                this->IceVolumex(&double_result);                break;
+				case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(&double_result); break;
+				case MinVelEnum:                   this->MinVelx(&double_result);                   break;
+				case MaxVelEnum:                   this->MaxVelx(&double_result);                   break;
+				case MinVxEnum:                    this->MinVxx(&double_result);                    break;
+				case MaxVxEnum:                    this->MaxVxx(&double_result);                    break;
+				case MaxAbsVxEnum:                 this->MaxAbsVxx(&double_result);                 break;
+				case MinVyEnum:                    this->MinVyx(&double_result);                    break;
+				case MaxVyEnum:                    this->MaxVyx(&double_result);                    break;
+				case MaxAbsVyEnum:                 this->MaxAbsVyx(&double_result);                 break;
+				case MinVzEnum:                    this->MinVzx(&double_result);                    break;
+				case MaxVzEnum:                    this->MaxVzx(&double_result);                    break;
+				case MaxAbsVzEnum:                 this->MaxAbsVzx(&double_result);                 break;
+				case MassFluxEnum:                 this->MassFluxx(&double_result);                 break;
+				case TotalSmbEnum:                 this->TotalSmbx(&double_result);                 break;
+
+			   /*Scalar control output*/
+				#ifdef _HAVE_CONTROL_
+				case SurfaceAbsVelMisfitEnum:       SurfaceAbsVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceRelVelMisfitEnum:       SurfaceRelVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceLogVelMisfitEnum:       SurfaceLogVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceLogVxVyMisfitEnum:      SurfaceLogVxVyMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);       break;
+				case SurfaceAverageVelMisfitEnum:   SurfaceAverageVelMisfitx(&double_result,this);                                                  break;
+				case ThicknessAbsMisfitEnum:        ThicknessAbsMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);         break;
+				case ThicknessAbsGradientEnum:      this->ThicknessAbsGradientx(&double_result);                                                    break;
+				case ThicknessAlongGradientEnum:    ThicknessAlongGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);     break;
+				case ThicknessAcrossGradientEnum:   ThicknessAcrossGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
+				case RheologyBbarAbsGradientEnum:   RheologyBbarAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
+				case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters); break;
+				case BalancethicknessMisfitEnum:    BalancethicknessMisfitx(&double_result);                                                        break;
+				#endif
+
+			   /*Vector */
+				default:
+
+					/*Vector layout*/
+					int interpolation,size;
+
+					/*Get interpolation (and compute input if necessary)*/
+					for(int j=0;j<elements->Size();j++){
+						Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
+						element->ResultInterpolation(&interpolation,output_enum);
+					}
+
+					/*Allocate vector depending on interpolation*/
+					switch(interpolation){
+						case P0Enum: size = this->elements->NumberOfElements(); break;
+						case P1Enum: size = this->vertices->NumberOfVertices(); break;
+						default:     _error_("Interpolation "<<EnumToStringx(interpolation)<<" not supported yet");
+
+					}
+					Vector<IssmPDouble> *vector_result = new Vector<IssmPDouble>(this->vertices->NumberOfVertices());
+
+					/*Fill in vector*/
+					for(int j=0;j<elements->Size();j++){
+						Element* element=(Element*)elements->GetObjectByOffset(j);
+						element->ResultToVector(vector_result,output_enum);
+					}
+					vector_result->Assemble();
+
+					results->AddResult(new GenericExternalResult<Vector<IssmPDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
+					isvec = true;
 					break;
-				case TotalSmbEnum:
-					Responsex(&output_value,"TotalSmb",0);
-					results->AddObject(new GenericExternalResult<double>(results->Size()+1,TotalSmbEnum,reCast<IssmPDouble>(output_value),step,time));
-					break;
-				case MaxVelEnum:
-					Responsex(&output_value,"MaxVel",0);
-					results->AddObject(new GenericExternalResult<double>(results->Size()+1,MaxVelEnum,reCast<IssmPDouble>(output_value),step,time));
-					break;
-				default:
-					/*create this output in the element inputs, and then transfer to results:*/
-					for(int j=0;j<elements->Size();j++){
-						element=(Element*)elements->GetObjectByOffset(j);
-						element->RequestedOutput(output_enum,step,time);
-					}
-					break;
+
+				#else
+				default: _error_("ISSM was not compiled with responses capabilities, exiting!");
+				#endif
 			}
 		}
-	}
+
+		/*Add result to Results*/
+		if(!isvec){
+			results->AddResult(new GenericExternalResult<IssmPDouble>(results->Size()+1,output_string,reCast<IssmPDouble>(double_result),step,time));
+		}
+	}
+
+	/*Assign pointer and clean up*/
+	*presults = results;
+}
+/*}}}*/
+void FemModel::RequestedOutputsx(Results **presults,int* requested_outputs, int numoutputs){/*{{{*/
+
+	/*Convert list of enums to list of string*/
+	char** enumlist = xNew<char*>(numoutputs);
+	for(int i=0;i<numoutputs;i++){
+		EnumToStringx(&enumlist[i],requested_outputs[i]);
+	}
+
+	/*Call main module*/
+	this->RequestedOutputsx(presults,enumlist,numoutputs);
+
+	/*clean up and return*/
+	for(int i=0;i<numoutputs;i++) xDelete<char>(enumlist[i]);
+	xDelete<char*>(enumlist);
+	return;
 }
 /*}}}*/
@@ -543,4 +638,5 @@
 		}
 		delete dependent_objects;
+		if(num_dependents)xDelete<IssmPDouble>(dependents);
 		#else
 		_error_("Should not be requesting dependents when an AD library is not available!");
@@ -577,4 +673,22 @@
 	/*Assign output pointers:*/
 	*pdt=min_dt;
+}
+/*}}}*/
+void FemModel::UpdateConstraintsExtrudeFromBasex(void){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->UpdateConstraintsExtrudeFromBase();
+	}
+
+}
+/*}}}*/
+void FemModel::UpdateConstraintsExtrudeFromTopx(void){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->UpdateConstraintsExtrudeFromTop();
+	}
+
 }
 /*}}}*/
@@ -934,4 +1048,20 @@
 
 }/*}}}*/
+void FemModel::IceVolumeAboveFloatationx(IssmDouble* pV){/*{{{*/
+
+	IssmDouble local_ice_volume_af = 0;
+	IssmDouble total_ice_volume_af;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		local_ice_volume_af+=element->IceVolumeAboveFloatation();
+	}
+	ISSM_MPI_Reduce(&local_ice_volume_af,&total_ice_volume_af,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_ice_volume_af,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pV=total_ice_volume_af;
+
+}/*}}}*/
 void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum){/*{{{*/
 
@@ -976,5 +1106,5 @@
 #endif
 #ifdef _HAVE_CONTROL_
-void FemModel::BalancethicknessMisfitx(IssmDouble* presponse,int weight_index){/*{{{*/
+void FemModel::BalancethicknessMisfitx(IssmDouble* presponse){/*{{{*/
 
 	IssmDouble J = 0;
@@ -983,5 +1113,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		J+=element->BalancethicknessMisfit(weight_index);
+		J+=element->BalancethicknessMisfit();
 	}
 	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -993,5 +1123,5 @@
 
 }/*}}}*/
-void FemModel::ThicknessAbsGradientx( IssmDouble* pJ, int weight_index){/*{{{*/
+void FemModel::ThicknessAbsGradientx( IssmDouble* pJ){/*{{{*/
 
 	/*Intermediary*/
@@ -1006,5 +1136,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAbsGradient(weight_index);
+		J+=element->ThicknessAbsGradient();
 	}
 
@@ -1022,27 +1152,78 @@
 	/*Intermediary*/
 	int      num_responses;
-	Element *element       = NULL;
-	int     *responses     = NULL;
-
-	/*output: */
-	IssmDouble J,Jplus;
+	int     *responses      = NULL;
+	Results *cost_functions = NULL;
 
 	/*Recover parameters*/
 	parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
-
-	/*Get response*/
-	J=0;
-	//_printf_(true,"list of misfits: ");
+	parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Get the value of all cost functions*/
+	this->RequestedOutputsx(&cost_functions,responses,num_responses);
+
+	/*Add all contributions one by one*/
+	IssmDouble J=0;
+	//_printf0_("list of misfits: ");
 	for(int i=0;i<num_responses;i++){
-		this->Responsex(&Jplus,EnumToStringx(responses[i]),i);
-		//_printf_(true," %12.7g ",Jplus);
-		J+=Jplus;
-	}
-	//_printf_(true," \n");
+		ExternalResult* result=(ExternalResult*)cost_functions->GetObjectByOffset(i);
+		J += reCast<IssmDouble>(result->GetValue());
+		//_printf0_(J<<" ");
+	}
+	//_printf0_(" \n");
+	_assert_(cost_functions->Size()==num_responses);
 
 	/*Assign output pointers: */
+	delete cost_functions;
 	xDelete<int>(responses);
 	*pJ=J;
+}
+/*}}}*/
+void FemModel::OutputControlsx(Results **presults){/*{{{*/
+
+	/*parameters: */
+	int         num_controls,step;
+	IssmDouble  time;
+	int        *control_type = NULL;
+
+	/*recover results*/
+	Results* results = *presults;
+	if(!results) results = new Results();
+
+	/*Get list of Controls*/
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	this->parameters->FindParam(&step,StepEnum);
+	this->parameters->FindParam(&time,TimeEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		int control_enum = control_type[i];
+		int gradient_enum;
+
+		switch(i){
+			case 0: gradient_enum = Gradient1Enum; break;
+			case 1: gradient_enum = Gradient2Enum; break;
+			case 2: gradient_enum = Gradient3Enum; break;
+			default: _error_("more than 3 controls not implemented yet");
+		}
+
+		/*Allocate vector*/
+		Vector<IssmPDouble> *vector_control  = new Vector<IssmPDouble>(this->vertices->NumberOfVertices());
+		Vector<IssmPDouble> *vector_gradient = new Vector<IssmPDouble>(this->vertices->NumberOfVertices());
+
+		/*Fill in vector*/
+		for(int j=0;j<elements->Size();j++){
+			Element* element=(Element*)elements->GetObjectByOffset(j);
+			element->ControlToVectors(vector_control,vector_gradient,control_enum);
+		}
+		vector_control->Assemble();
+		vector_gradient->Assemble();
+
+		results->AddResult(new GenericExternalResult<Vector<IssmPDouble>*>(results->Size()+1,control_enum,vector_control ,step,time));
+		results->AddResult(new GenericExternalResult<Vector<IssmPDouble>*>(results->Size()+1,gradient_enum,vector_gradient,step,time));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
 }
 /*}}}*/
@@ -1105,5 +1286,5 @@
 			parameters->SetParam(index,IndexEnum);
 
-			this->Responsex(&femmodel_response,root,0);//0 is the index for weights
+			this->Responsex(&femmodel_response,root);
 
 			if(my_rank==0){
@@ -1124,5 +1305,5 @@
 
 			/*perfectly normal response function: */
-			this->Responsex(&femmodel_response,root,0);//0 is the weight index
+			this->Responsex(&femmodel_response,root);
 
 			if(my_rank==0){
@@ -1152,12 +1333,7 @@
 void FemModel::Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y){ /*{{{*/
 
-  int      i;
-
-	/*intermediary: */
-	Element *element     = NULL;
-
 	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	for (i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->GiaDeflection(wg,dwgdt, x,y);
 	}
@@ -1247,13 +1423,2 @@
 /*}}}*/
 #endif
-#ifdef _HAVE_THERMAL_
-void FemModel::UpdateThermalBasalConstraintsx(void){ /*{{{*/
-
-	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->UpdateThermalBasalConstraints();
-	}
-
-}
-/*}}}*/
-#endif
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 16559)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 16560)
@@ -75,17 +75,20 @@
 		void TotalSmbx(IssmDouble* pSmb);
 		void IceVolumex(IssmDouble* pV);
+		void IceVolumeAboveFloatationx(IssmDouble* pV);
 		void ElementResponsex(IssmDouble* presponse,int response_enum);
-		void BalancethicknessMisfitx(IssmDouble* pV,int weight_index);
+		void BalancethicknessMisfitx(IssmDouble* pV);
 		#endif
 		#ifdef  _HAVE_DAKOTA_
 		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
 		#endif
-		void RequestedOutputsx(int* requested_outputs, int numoutputs);
+		void RequestedOutputsx(Results **presults,char** requested_outputs, int numoutputs);
+		void RequestedOutputsx(Results **presults,int* requested_outputs, int numoutputs);
 		void RequestedDependentsx(void);
-		void Responsex(IssmDouble* presponse,int response_descriptor_enum,int weight_index);
-		void Responsex(IssmDouble* presponse,const char* response_descriptor,int weight_index);
+		void Responsex(IssmDouble* presponse,int response_descriptor_enum);
+		void Responsex(IssmDouble* presponse,const char* response_descriptor);
 		#ifdef _HAVE_CONTROL_
+		void OutputControlsx(Results **presults);
 		void CostFunctionx( IssmDouble* pJ);
-		void ThicknessAbsGradientx( IssmDouble* pJ,int weight_index);
+		void ThicknessAbsGradientx( IssmDouble* pJ);
 		#endif
 		#ifdef _HAVE_GIA_
@@ -95,11 +98,10 @@
 		void UpdateConstraintsx(void);
 		int  UpdateVertexPositionsx(void);
+		void UpdateConstraintsExtrudeFromBasex();
+		void UpdateConstraintsExtrudeFromTopx();
 		#ifdef _HAVE_HYDROLOGY_
 		void HydrologyTransferx(void);
 		void HydrologyEPLupdateDomainx(void);
 		#endif
-		#ifdef _HAVE_THERMAL_
-		void UpdateThermalBasalConstraintsx(void);
-		#endif
 };
 
Index: /issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 16560)
@@ -206,14 +206,4 @@
 }
 /*}}}*/
-/*FUNCTION Hook::GetObjects{{{*/
-Object** Hook::GetObjects(void){
-	return this->objects;
-}
-/*}}}*/
-/*FUNCTION Hook::GetOffsets{{{*/
-int* Hook::GetOffsets(void){
-	return this->offsets;
-}
-/*}}}*/
 /*FUNCTION Hook::Spawn{{{*/
 Hook* Hook::Spawn(int* indices, int numindices){
Index: /issm/trunk/src/c/classes/Hook.h
===================================================================
--- /issm/trunk/src/c/classes/Hook.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Hook.h	(revision 16560)
@@ -40,7 +40,5 @@
 		void       configure(DataSet* dataset);
 		Hook*      Spawn(int* indices, int numindices);
-		Object**   GetObjects(void);
 		int*       Ids(void);
-		int*       GetOffsets(void);
 		int        GetNum(void);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/IndependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 16560)
@@ -106,10 +106,9 @@
 		if(my_rank==0){
 			if(fread(&pscalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
-			
+
 			/*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!: */
 			scalar<<=pscalar;
 		}
 
-		
 		ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
 
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 16560)
@@ -86,8 +86,16 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::SpawnResult{{{*/
-ElementResult* BoolInput::SpawnResult(int step, IssmDouble time){
+/*FUNCTION BoolInput::SpawnSegInput{{{*/
+Input* BoolInput::SpawnSegInput(int index1,int index2){
 
-	return new BoolElementResult(this->enum_type,this->value,step,time);
+		/*output*/
+		BoolInput* outinput=new BoolInput();
+
+		/*only copy current value*/
+		outinput->enum_type=this->enum_type;
+		outinput->value=this->value;
+
+		/*Assign output*/
+		return outinput;
 
 }
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 16560)
@@ -35,8 +35,9 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int  GetResultInterpolation(void){return P0Enum;};
 		void Configure(Parameters* parameters);
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
@@ -46,4 +47,5 @@
 		void GetInputValue(int* pvalue);
 		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -52,4 +54,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -72,6 +75,6 @@
 		IssmDouble Min(void){_error_("Min not implemented for booleans");};
 		IssmDouble MinAbs(void){_error_("Min not implemented for booleans");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 16560)
@@ -139,4 +139,11 @@
 	//gradient->Extrude();
 }/*}}}*/
+/*FUNCTION ControlInput::GetResultInterpolation{{{*/
+int  ControlInput::GetResultInterpolation(void){
+
+	return values->GetResultInterpolation();
+
+}
+/*}}}*/
 /*FUNCTION ControlInput::GetGradient{{{*/
 void ControlInput::GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){
@@ -178,16 +185,11 @@
 
 }/*}}}*/
-/*FUNCTION ControlInput::SpawnResult{{{*/
-ElementResult* ControlInput::SpawnResult(int step, IssmDouble time){
-	return savedvalues->SpawnResult(step,time);
-}/*}}}*/
 /*FUNCTION ControlInput::SpawnTriaInput{{{*/
 Input* ControlInput::SpawnTriaInput(int location){
 	return values->SpawnTriaInput(location);
 }/*}}}*/
-/*FUNCTION ControlInput::SpawnGradient{{{*/
-ElementResult* ControlInput::SpawnGradient(int step, IssmDouble time){
-	_assert_(gradient);
-	return gradient->SpawnResult(step,time);
+/*FUNCTION ControlInput::SpawnSegInput{{{*/
+Input* ControlInput::SpawnSegInput(int index1,int index2){
+	return values->SpawnSegInput(index1,index2);
 }/*}}}*/
 /*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){{{*/
@@ -241,4 +243,12 @@
 	values->GetInputValue(pvalue,gauss);
 }/*}}}*/
+/*FUNCTION ControlInput::GetGradientValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void ControlInput::GetGradientValue(IssmDouble* pvalue,GaussTria* gauss){
+	gradient->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetGradientValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void ControlInput::GetGradientValue(IssmDouble* pvalue,GaussPenta* gauss){
+	gradient->GetInputValue(pvalue,gauss);
+}/*}}}*/
 /*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
 void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 16560)
@@ -39,16 +39,19 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time);
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
 		/*numerics: {{{*/
+		void GetGradientValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetGradientValue(IssmDouble* pvalue,GaussPenta* gauss);
 		void SetInput(Input* in_input);
 		void GetInputValue(bool* pvalue);
 		void GetInputValue(int* pvalue);
 		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -57,4 +60,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -72,6 +76,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
 		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(void);
@@ -86,5 +90,5 @@
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		ElementResult* SpawnGradient(int step, IssmDouble time);
+		int  GetResultInterpolation(void);
 		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist);
 		void ScaleGradient(IssmDouble scale);
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 16560)
@@ -16,17 +16,22 @@
 /*FUNCTION DatasetInput::DatasetInput(){{{*/
 DatasetInput::DatasetInput(){
-	enum_type=UNDEF;
-	inputs=NULL;
+	enum_type = UNDEF;
+	inputs    = NULL;
+	numids    = 0;
+	ids       = NULL;
 }
 /*}}}*/
-/*FUNCTION DatasetInput::DatasetInput(int in_enum_type) {{{*/
+/*FUNCTION DatasetInput::DatasetInput(int in_enum_type,int* idlist,int numids) {{{*/
 DatasetInput::DatasetInput(int in_enum_type){
 
-	enum_type  = in_enum_type;
-	inputs     = new Inputs();
+	enum_type = in_enum_type;
+	numids    = 0;
+	inputs    = new Inputs();
+	ids       = NULL;
 }
 /*}}}*/
 /*FUNCTION DatasetInput::~DatasetInput(){{{*/
 DatasetInput::~DatasetInput(){
+	xDelete<int>(this->ids);
 	delete inputs;
 }
@@ -44,5 +49,9 @@
 	_printf_("DatasetInput:\n");
 	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
-	_printf_("---inputs: \n"); inputs->Echo();
+	_printf_("   numids:"<< this->numids<< "\n");
+	_printf_("      ids: ");
+	for(int i=0;i<this->numids;i++) _printf_(this->ids[i]<<" ");
+	_printf_("\n");
+	_printf_("   inputs: \n"); inputs->Echo();
 }
 /*}}}*/
@@ -79,4 +88,25 @@
 	outinput->enum_type=this->enum_type;
 	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(location));
+	outinput->numids=this->numids;
+	outinput->ids=xNew<int>(this->numids);
+	xMemCpy(outinput->ids,this->ids,this->numids);
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::SpawnSegInput{{{*/
+Input* DatasetInput::SpawnSegInput(int index1,int index2){
+
+	/*output*/
+	DatasetInput* outinput=NULL;
+
+	/*Create new Datasetinput (copy of current input)*/
+	outinput=new DatasetInput();
+	outinput->enum_type=this->enum_type;
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnSegInputs(index1,index2));
+	outinput->numids=this->numids;
+	outinput->ids=xNew<int>(this->numids);
+	xMemCpy(outinput->ids,this->ids,this->numids);
 
 	/*Assign output*/
@@ -86,4 +116,32 @@
 
 /*DatasetInput management*/
+/*FUNCTION DatasetInput::AddInput{{{*/
+void DatasetInput::AddInput(Input* input,int id){
+
+	_assert_(this->numids == this->inputs->Size());
+
+	int *old_ids = NULL;
+
+	if(this->numids>0){
+		old_ids=xNew<int>(this->numids);
+		xMemCpy(old_ids,this->ids,this->numids);
+		xDelete<int>(this->ids);
+	}
+
+	this->numids=this->numids+1;
+	this->ids=xNew<int>(this->numids);
+
+	if(this->numids>1){
+		xMemCpy(this->ids,old_ids,this->numids-1);
+		xDelete<int>(old_ids);
+	}
+
+	/*go ahead and plug: */
+	this->ids[this->numids-1]=id;
+	inputs->AddObject(input);
+
+	_assert_(this->numids == this->inputs->Size());
+}
+/*}}}*/
 /*FUNCTION DatasetInput::InstanceEnum{{{*/
 int DatasetInput::InstanceEnum(void){
@@ -100,21 +158,29 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int index){{{*/
-void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int index){
+/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int id){{{*/
+void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int id){
+
+	int  offset = -1;
+	_assert_(this->numids == this->inputs->Size());
 
 	/*Get requested input within dataset*/
-	if(index<0 || index > inputs->Size()-1) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
-	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(index));
+	for(int i=0;i<this->numids;i++) if(this->ids[i]==id) offset=i;
+	if(offset<0) _error_("Could not find input of id "<<id);
 
+	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(offset));
 	input->GetInputValue(pvalue,gauss);
 }
 /*}}}*/
-/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){{{*/
-void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){
+/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int id){{{*/
+void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int id){
+
+	int  offset = -1;
+	_assert_(this->numids == this->inputs->Size());
 
 	/*Get requested input within dataset*/
-	if(index<0 || index > inputs->Size()-1) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
-	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(index));
+	for(int i=0;i<this->numids;i++) if(this->ids[i]==id) offset=i;
+	if(offset<0) _error_("Could not find input of id "<<id);
 
+	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(offset));
 	input->GetInputValue(pvalue,gauss);
 }
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 16560)
@@ -17,5 +17,7 @@
 	public:
 		int     enum_type;
+		int     numids;
 		Inputs *inputs;
+		int    *ids;
 
 		/*DatasetInput constructors, destructors: {{{*/
@@ -32,10 +34,11 @@
 		/*}}}*/
 		/*DatasetInput management: {{{*/
+		void   AddInput(Input* input,int id);
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time){_error_("not implemented yet");};
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
@@ -45,4 +48,5 @@
 		void GetInputValue(int* pvalue){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
@@ -51,4 +55,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
@@ -66,6 +71,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
 		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
 		void Constrain(void){_error_("not implemented yet");};
@@ -79,5 +84,5 @@
 		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
-		ElementResult* SpawnGradient(int step, IssmDouble time){_error_("not implemented yet");};
+		int GetResultInterpolation(void){_error_("not implemented yet");};
 		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){_error_("not implemented yet");};
 		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 16560)
@@ -86,8 +86,16 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::SpawnResult{{{*/
-ElementResult* DoubleInput::SpawnResult(int step, IssmDouble time){
-
-	return new DoubleElementResult(this->enum_type,this->value,step,time);
+/*FUNCTION DoubleInput::SpawnSegInput{{{*/
+Input* DoubleInput::SpawnSegInput(int index1,int index2){
+
+	/*output*/
+	DoubleInput* outinput=new DoubleInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
 
 }
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 16560)
@@ -34,8 +34,9 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB);
 		Input* PointwiseMin(Input* inputB);
 		Input* PointwiseMax(Input* inputB);
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int  GetResultInterpolation(void){return P0Enum;};
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
@@ -45,4 +46,5 @@
 		void GetInputValue(int* pvalue);
 		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -51,4 +53,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -66,6 +69,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
 		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
Index: /issm/trunk/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Input.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/Input.h	(revision 16560)
@@ -11,6 +11,6 @@
 #include "../../shared/shared.h"
 class Node;
-class ElementResult;
 class GaussTria;
+class GaussSeg;
 class Parameters;
 class GaussPenta;
@@ -28,4 +28,5 @@
 		virtual void GetInputValue(int* pvalue)=0;
 		virtual void GetInputValue(IssmDouble* pvalue)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss)=0;
 		virtual void GetInputValue(IssmDouble* pvalue,GaussTria* gauss)=0;
 		virtual void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss)=0;
@@ -34,4 +35,5 @@
 		virtual void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index)=0;
 		virtual void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index)=0;
+		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss)=0;
 		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss)=0;
 		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss)=0;
@@ -56,6 +58,6 @@
 		virtual IssmDouble Max(void)=0;
 		virtual IssmDouble Min(void)=0;
+		virtual void Set(IssmDouble setvalue)=0;
 		virtual void   Scale(IssmDouble scale_factor)=0;
-		virtual void   ArtificialNoise(IssmDouble min,IssmDouble max)=0;
 		virtual void   AXPY(Input* xinput,IssmDouble scalar)=0;
 		virtual void   Constrain(IssmDouble cm_min, IssmDouble cm_max)=0;
@@ -65,8 +67,9 @@
 
 		virtual Input* SpawnTriaInput(int location)=0;
+		virtual Input* SpawnSegInput(int index1,int index2)=0;
 		virtual Input* PointwiseDivide(Input* inputB)=0;
 		virtual Input* PointwiseMax(Input* inputmax)=0;
 		virtual Input* PointwiseMin(Input* inputmin)=0;
-		virtual ElementResult* SpawnResult(int step, IssmDouble time)=0;
+		virtual int GetResultInterpolation(void)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 16560)
@@ -395,14 +395,40 @@
 }
 /*}}}*/
+/*FUNCTION Inputs::SpawnSegInputs{{{*/
+Inputs* Inputs::SpawnSegInputs(int index1,int index2){
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	Input* inputin=NULL;
+	Input* inputout=NULL;
+
+	/*Output*/
+	Inputs* newinputs=new Inputs();
+
+	/*Go through inputs and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new input*/
+		inputin=dynamic_cast<Input*>(*object);
+		inputout=inputin->SpawnSegInput(index1,index2);
+
+		/*Add input to new inputs*/
+		newinputs->AddObject(inputout);
+	}
+
+	/*Assign output pointer*/
+	return newinputs;
+}
+/*}}}*/
 /*FUNCTION Inputs::AXPY{{{*/
-void  Inputs::AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum){
+void  Inputs::AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum){
 
 	/*Find x and y inputs: */
-	Input* xinput=dynamic_cast<Input*>(this->GetInput(MeshXEnum));
-	Input* yinput=dynamic_cast<Input*>(this->GetInput(MeshYEnum));
+	Input* xinput=dynamic_cast<Input*>(this->GetInput(inputx_enum));
+	Input* yinput=dynamic_cast<Input*>(this->GetInput(inputy_enum));
 
 	/*some checks: */
-	if(!xinput) _error_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
-	if(!yinput) _error_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
+	if(!xinput) _error_("input " << EnumToStringx(inputx_enum) << " could not be found!");
+	if(!yinput) _error_("input " << EnumToStringx(inputy_enum) << " could not be found!");
 
 	/*Apply AXPY: */
Index: /issm/trunk/src/c/classes/Inputs/Inputs.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 16560)
@@ -22,12 +22,14 @@
 
 		/*numerics*/
-		int        AddInput(Input* in_input);
-		void       ChangeEnum(int enumtype,int new_enumtype);
-		void       ConstrainMin(int constrain_enum, IssmDouble minimum);
-		int        DeleteInput(int enum_type);
-		void       DuplicateInput(int original_enum,int new_enum);
-		Input*     GetInput(int enum_name);
-		Inputs*    SpawnTriaInputs(int position);
-		void       AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
+		int         AddInput(Input* in_input);
+		void        ChangeEnum(int enumtype,int new_enumtype);
+		void        ConstrainMin(int constrain_enum, IssmDouble minimum);
+		int         DeleteInput(int enum_type);
+		void        DuplicateInput(int original_enum,int new_enum);
+		Input*      GetInput(int enum_name);
+		Inputs*     SpawnTriaInputs(int position);
+		Inputs*     SpawnSegInputs(int index1,int index2);
+		Inputs*     SpawnSegInputs(int position);
+		void        AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum);
 		IssmDouble  InfinityNorm(int enumtype);
 		IssmDouble  Max(int enumtype);
@@ -35,9 +37,9 @@
 		IssmDouble  Min(int enumtype);
 		IssmDouble  MinAbs(int enumtype);
-		void GetInputAverage(IssmDouble* pvalue, int enum_type);
-		void GetInputValue(bool* pvalue,int enum_type);
-		void GetInputValue(int* pvalue,int enum_type);
-		void GetInputValue(IssmDouble* pvalue,int enum_type);
-		void Configure(Parameters* parameters);
+		void        GetInputAverage(IssmDouble* pvalue, int enum_type);
+		void        GetInputValue(bool* pvalue,int enum_type);
+		void        GetInputValue(int* pvalue,int enum_type);
+		void        GetInputValue(IssmDouble* pvalue,int enum_type);
+		void        Configure(Parameters* parameters);
 
 };
Index: /issm/trunk/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 16560)
@@ -85,9 +85,16 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::SpawnResult{{{*/
-ElementResult* IntInput::SpawnResult(int step, IssmDouble time){
+/*FUNCTION IntInput::SpawnSegInput{{{*/
+Input* IntInput::SpawnSegInput(int index1,int index2){
 
-	_error_("not supported yet!");
+	/*output*/
+	IntInput* outinput=new IntInput();
 
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 16560)
@@ -35,8 +35,9 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int  GetResultInterpolation(void){return P0Enum;};
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
@@ -46,4 +47,5 @@
 		void GetInputValue(int* pvalue);
 		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -52,4 +54,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -68,6 +71,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
 		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 16560)
@@ -124,8 +124,14 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::SpawnResult{{{*/
-ElementResult* PentaInput::SpawnResult(int step, IssmDouble time){
-
-	return new PentaP1ElementResult(this->enum_type,this->values,step,time);
+/*FUNCTION PentaInput::SpawnSegInput{{{*/
+Input* PentaInput::SpawnSegInput(int index1,int index2){
+
+	_error_("not supported");
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetResultInterpolation{{{*/
+int  PentaInput::GetResultInterpolation(void){
+
+	return P1Enum;
 
 }
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 16560)
@@ -35,8 +35,9 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* inputB);
 		Input* PointwiseMin(Input* inputB);
 		Input* PointwiseMax(Input* inputB);
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int  GetResultInterpolation(void);
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
@@ -45,4 +46,5 @@
 		void GetInputValue(int* pvalue){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -51,4 +53,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -68,6 +71,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
 		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
Index: /issm/trunk/src/c/classes/Inputs/SegInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 16560)
+++ /issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 16560)
@@ -0,0 +1,119 @@
+/*!\file SegInput.c
+ * \brief: implementation of the SegInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*SegInput constructors and destructor*/
+/*FUNCTION SegInput::SegInput(){{{*/
+SegInput::SegInput(){
+	values = NULL;
+}
+/*}}}*/
+/*FUNCTION SegInput::SegInput(int in_enum_type,IssmDouble* invalues,element_type_in){{{*/
+SegInput::SegInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
+	:SegRef(1)
+{
+
+	/*Set SegRef*/
+	this->SetElementType(element_type_in,0);
+	this->element_type=element_type_in;
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes());
+	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
+}
+/*}}}*/
+/*FUNCTION SegInput::~SegInput(){{{*/
+SegInput::~SegInput(){
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION SegInput::Echo {{{*/
+void SegInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION SegInput::DeepEcho{{{*/
+void SegInput::DeepEcho(void){
+
+	_printf_("SegInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   values: [");
+	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
+	_printf_("]\n");
+}
+/*}}}*/
+/*FUNCTION SegInput::Id{{{*/
+int    SegInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION SegInput::ObjectEnum{{{*/
+int SegInput::ObjectEnum(void){
+
+	return SegInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION SegInput::copy{{{*/
+Object* SegInput::copy() {
+
+	return new SegInput(this->enum_type,this->values,this->element_type);
+
+}
+/*}}}*/
+
+/*SegInput management*/
+/*FUNCTION SegInput::InstanceEnum{{{*/
+int SegInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION SegInput::GetInputAverage{{{*/
+void SegInput::GetInputAverage(IssmDouble* pvalue){
+
+	int        numnodes  = this->NumberofNodes();
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION SegInput::GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){{{*/
+void SegInput::GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){
+
+	/*Call SegRef function*/
+	SegRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussSeg* gauss){{{*/
+void SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussSeg* gauss){
+
+	/*Call SegRef function*/
+	SegRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION SegInput::Configure{{{*/
+void SegInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/SegInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 16560)
+++ /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 16560)
@@ -0,0 +1,87 @@
+/*! \file SegInput.h 
+ *  \brief: header file for SegInput object
+ */
+
+#ifndef _SEGINPUT_H_
+#define _SEGINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/SegRef.h"
+class GaussSeg;
+class GaussPenta;
+/*}}}*/
+
+class SegInput: public Input,public SegRef{
+
+	public:
+		int         enum_type;
+		IssmDouble* values;
+
+		/*SegInput constructors, destructors*/
+		SegInput();
+		SegInput(int enum_type,IssmDouble* values,int element_type_in);
+		~SegInput();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*SegInput management:*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int location){_error_("not supported yet");};
+		Input* SpawnSegInput(int index1,int index2){_error_("not implemented yet");};
+		Input* PointwiseDivide(Input* inputB){_error_("not supported yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not supported yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not supported yet");};
+		int  GetResultInterpolation(void){_error_("not implemented");};
+		void   AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void   Configure(Parameters* parameters);
+
+		/*numerics*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
+
+};
+#endif  /* _SEGINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 16560)
@@ -127,18 +127,22 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::SpawnResult{{{*/
-ElementResult* TransientInput::SpawnResult(int step, IssmDouble time){
-
-	ElementResult* elementresult=NULL;
-
-	/*Ok, we want to spawn an ElementResult. We have the time, just get 
-	 *the correct values: */
-	Input* input=GetTimeInput(time);
-
-	elementresult=input->SpawnResult(step,time);
-
-   delete input;
-
-	return elementresult;
+/*FUNCTION TransientInput::SpawnSegInput{{{*/
+Input* TransientInput::SpawnSegInput(int index1,int index2){
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+	outinput->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
 }
 /*}}}*/
@@ -267,10 +271,9 @@
 void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
 
-	int i;
-	IssmDouble* times=NULL;
-	IssmDouble* values=NULL;
-	int numsteps;
-	int count;
-	bool iscurrenttime_included=false;
+	int         i;
+	IssmDouble *times  = NULL;
+	IssmDouble *values = NULL;
+	int         numsteps;
+	bool        iscurrenttime_included = false;
 
 	/*Figure out how many time steps we are going to return: */
@@ -339,4 +342,14 @@
 }
 /*}}}*/
+/*FUNCTION TransientInput::GetResultInterpolation{{{*/
+int  TransientInput::GetResultInterpolation(void){
+
+	IssmDouble time;
+	parameters->FindParam(&time,TimeEnum);
+	Input* input=GetTimeInput(time);
+	return input->GetResultInterpolation();
+
+}
+/*}}}*/
 /*FUNCTION TransientInput::Extrude{{{*/
 void TransientInput::Extrude(void){
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 16560)
@@ -39,8 +39,9 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int location);
+		Input* SpawnSegInput(int index1,int index2);
 		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
 		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int  GetResultInterpolation(void);
 		void Configure(Parameters* parameters);
 		/*}}}*/
@@ -49,4 +50,5 @@
 		void GetInputValue(int* pvalue){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
@@ -55,4 +57,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
@@ -71,6 +74,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
 		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 16560)
@@ -97,8 +97,28 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::SpawnResult{{{*/
-ElementResult* TriaInput::SpawnResult(int step, IssmDouble time){
-
-	return new TriaP1ElementResult(this->enum_type,this->values,step,time);
+/*FUNCTION TriaInput::SpawnSegInput{{{*/
+Input* TriaInput::SpawnSegInput(int index1,int index2){
+
+	/*output*/
+	SegInput* outinput=NULL;
+	IssmDouble newvalues[2]; //Assume P1 interpolation only for now
+
+	/*Create arrow of indices depending on location (0=base 1=surface)*/
+
+	newvalues[0]=this->values[index1];
+	newvalues[1]=this->values[index2];
+
+	/*Create new Seg input*/
+	outinput=new SegInput(this->enum_type,&newvalues[0],P1Enum);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetResultInterpolation{{{*/
+int  TriaInput::GetResultInterpolation(void){
+
+	return P1Enum;
 
 }
@@ -321,18 +341,9 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::ArtificialNoise{{{*/
-void TriaInput::ArtificialNoise(IssmDouble min,IssmDouble max){
-
-	int i;
+/*FUNCTION TriaInput::Set{{{*/
+void TriaInput::Set(IssmDouble setvalue){
+
 	const int numnodes=this->NumberofNodes();
-	IssmDouble noise;
-
-	/*Compute random number between bounds:
-	 * rand() outputs an integer in [0 RAND_MAX]
-	 * (IssmDouble)rand()/RAND_MAX is in [0 1]
-	 */
-	 noise=min+(max-min)*(IssmDouble)rand()/RAND_MAX;
-
-	for(i=0;i<numnodes;i++)values[i]=values[i]+noise;
+	for(int i=0;i<numnodes;i++)values[i]=setvalue;
 }
 /*}}}*/
@@ -435,4 +446,37 @@
 }
 /*}}}*/
+/*FUNCTION TriaInput::PointwiseDivide{{{*/
+Input* TriaInput::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	TriaInput *xinputB  = NULL;
+	const int   numnodes = this->NumberofNodes();
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TriaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaInput*)inputB;
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+
+	/*Allocate intermediary*/
+	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
+
+	/*Create point wise division*/
+	for(int i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,AdotBvalues,this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(AdotBvalues);
+	return outinput;
+
+}
+/*}}}*/
 /*FUNCTION TriaInput::Configure{{{*/
 void TriaInput::Configure(Parameters* parameters){
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 16560)
@@ -35,8 +35,9 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int location);
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB);
 		Input* PointwiseMin(Input* inputB);
 		Input* PointwiseMax(Input* inputB);
-		ElementResult* SpawnResult(int step, IssmDouble time);
+		int    GetResultInterpolation(void);
 		void   AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void   Configure(Parameters* parameters);
@@ -46,4 +47,5 @@
 		void GetInputValue(int* pvalue){_error_("not implemented yet");}
 		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
@@ -52,4 +54,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussSeg* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
@@ -68,6 +71,6 @@
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
 		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue);
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max);
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
Index: /issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 16560)
@@ -30,5 +30,5 @@
 	this->my_vertices=NULL;
 
-	this->dim=-1;
+	this->meshtype=-1;
 	this->numberofvertices=-1;
 	this->numberofelements=-1;
@@ -63,4 +63,5 @@
 	 *and prevent them from being erased during successive calls to iomodel->FetchConstants, iomodel->FetchData and 
 	 iomodel->DeleteData:*/
+	this->StartTrace();
 	this->DeclareIndependents();
 
@@ -73,5 +74,5 @@
 	this->my_vertices = NULL;
 
-	FetchData(&this->dim,MeshDimensionEnum);
+	FetchData(&this->meshtype,MeshTypeEnum);
 	FetchData(&this->numberofvertices,MeshNumberofverticesEnum);
 	FetchData(&this->numberofelements,MeshNumberofelementsEnum);
@@ -91,10 +92,20 @@
 IoModel::~IoModel(){
 
-	/*Some checks in debugging mode*/
+	/*Delete independents*/
+	if(this->independents){
+		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
+			if(this->independents[i]){
+				IssmDouble* array=this->data[i];
+				xDelete<IssmDouble>(array);
+			}
+		}
+	}
+
+	/*checks in debugging mode*/
 	#ifdef _ISSM_DEBUG_
 	if(this->data){
 		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
 			if(this->data[i]){
-				_printf0_("Info: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)\n");
+				_printf0_("WARNING: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)\n");
 			}
 		}
@@ -123,9 +134,8 @@
 void  IoModel::CheckEnumSync(void){
 
-	int my_rank;
-	int record_enum = 0;
+	int record_enum,record_length;
 
 	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
+	int my_rank=IssmComm::GetRank();
 
 	/*Check that some fields have been allocated*/
@@ -161,4 +171,47 @@
 			}
 		}
+
+		/*Get last enum*/
+		bool found     = false;
+		int  last_enum = 0;
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+		for(;;){
+			/*Have we reached the end of file ?*/
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				break;
+			}
+
+			/*Have we found the last Enum ?*/
+			if(record_enum==MaximumNumberOfDefinitionsEnum+1){
+				found = true;
+				break;
+			}
+
+			/*Check that record_enum is an enum*/
+			if(record_enum>=0 && record_enum<=MaximumNumberOfDefinitionsEnum){
+				if(record_enum>0) last_enum = record_enum;
+			}
+
+			/*Go to next Enum*/
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			fseek(fid,record_length,SEEK_CUR);
+		}
+		if(!found){
+			_printf0_("\n");
+			_printf0_("=========================================================================\n");
+			_printf0_(" Marshalled file is corrupted                                            \n");
+			_printf0_("                                                                         \n");
+			_printf0_("   * If you are running an old model, send it to the ISSM developers     \n");
+			_printf0_("     so that a check is added before marshall                            \n");
+			_printf0_("   * Last Enum found: " << EnumToStringx(last_enum)<<"Enum ("<<last_enum<<")\n");
+			_printf0_("     the corresponding model field has probably been marshalled          \n");
+			_printf0_("     incorrectly                                                         \n");
+			_printf0_("                                                                         \n");
+			_printf0_("=========================================================================\n");
+			_printf0_("\n");
+			_error_("Binary file corrupted (See error message above)");
+		}
 	}
 }
@@ -221,4 +274,44 @@
 }
 /*}}}*/
+/*FUNCTION IoModel::StartTrace{{{*/
+void IoModel::StartTrace(void){
+
+	int  i;
+	bool autodiff = false;
+	bool keep=false;
+	IssmDouble gcTriggerRatio;
+	IssmDouble gcTriggerMaxSize;
+	IssmDouble obufsize;
+	IssmDouble lbufsize;
+	IssmDouble cbufsize;
+	IssmDouble tbufsize;
+
+	int my_rank=IssmComm::GetRank();
+
+	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
+	if(autodiff){
+
+		#ifdef _HAVE_ADOLC_
+		/*Retrieve parameters: */
+		this->FetchData(&keep,AutodiffKeepEnum);
+		int keepTaylors=keep?1:0;
+		this->FetchData(&gcTriggerRatio,AutodiffGcTriggerRatioEnum);
+		this->FetchData(&gcTriggerMaxSize,AutodiffGcTriggerMaxSizeEnum);
+		this->FetchData(&obufsize,AutodiffObufsizeEnum);
+		this->FetchData(&lbufsize,AutodiffLbufsizeEnum);
+		this->FetchData(&cbufsize,AutodiffCbufsizeEnum);
+		this->FetchData(&tbufsize,AutodiffTbufsizeEnum);
+
+		/*Set garbage collection parameters: */
+		setStoreManagerControl(reCast<IssmPDouble>(gcTriggerRatio),reCast<size_t>(gcTriggerMaxSize));
+
+		/*Start trace: */
+		int skipFileDeletion=1;
+		trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
+		#endif
+	}
+
+}
+/*}}}*/
 /*FUNCTION IoModel::DeclareIndependents{{{*/
 void IoModel::DeclareIndependents(void){
@@ -232,7 +325,4 @@
 
 	int  dummy;
-	bool keep=false;
-
-	int my_rank=IssmComm::GetRank();
 
 	/*Initialize array detecting whether data[i] is an independent AD mode variable: */
@@ -244,9 +334,4 @@
 
 		#ifdef _HAVE_ADOLC_
-		/*Start trace*/
-		this->FetchData(&keep,AutodiffKeepEnum);
-		if(keep)trace_on(my_rank,1);
-		else    trace_on(my_rank);
-
 		/*build dataset made of independent objects:*/
 		this->independent_objects=new DataSet();
@@ -286,12 +371,9 @@
 	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);
+	for(int i=0;i<num;i++){
+		dataenum=va_arg(ap,int);
 		_assert_(dataenum<MaximumNumberOfDefinitionsEnum);
 
@@ -307,4 +389,19 @@
 	if(vector)if (!this->independents[dataenum]) xDelete<IssmDouble>(vector);
 
+} /*}}}*/
+/*FUNCTION IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum) {{{*/
+void  IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum){
+
+	int i;
+	char** stringarray=*pstringarray;
+	
+	if (numstrings){
+		for (i=0;i<numstrings;i++){
+			char* string=stringarray[i]; 
+			xDelete<char>(string);
+		}
+		xDelete<char*>(stringarray);
+	}
+	*pstringarray=NULL;
 } /*}}}*/
 /*FUNCTION IoModel::FetchConstants{{{*/
@@ -532,5 +629,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(bool*     pbool,int data_enum){{{*/
+/*FUNCTION IoModel::FetchData(bool*         pbool,int data_enum){{{*/
 void  IoModel::FetchData(bool* pboolean,int data_enum){
 
@@ -561,5 +658,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(int*      pinteger,int data_enum){{{*/
+/*FUNCTION IoModel::FetchData(int*          pinteger,int data_enum){{{*/
 void  IoModel::FetchData(int* pinteger,int data_enum){
 
@@ -617,5 +714,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(char**    pstring,int data_enum){{{*/
+/*FUNCTION IoModel::FetchData(char**        pstring,int data_enum){{{*/
 void  IoModel::FetchData(char** pstring,int data_enum){
 
@@ -664,5 +761,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(int**     pintegerematrix,int* pM,int* pN,int data_enum){{{*/
+/*FUNCTION IoModel::FetchData(int**         pintegerematrix,int* pM,int* pN,int data_enum){{{*/
 void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
 
@@ -682,5 +779,5 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 
-	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+	if(code!=5 && code!=6 && code!=7)_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum)<<" (Code is "<<code<<")");
 
 	/*Now fetch: */
@@ -748,5 +845,5 @@
 	/*Set file pointer to beginning of the data: */
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
-	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+	if(code!=5 && code!=6 && code!=7)_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum)<<" (Code is "<<code<<")");
 
 	/*Now fetch: */
@@ -775,5 +872,5 @@
 
 		_assert_(this->independents);
-		if (this->independents[data_enum]){
+		if(this->independents[data_enum]){
 			/*this data has already been checked out! So cancel all that we've done here, and return 
 			 * the data[data_enum] directly: */
@@ -782,5 +879,5 @@
 		else{
 			*pmatrix=xNew<IssmDouble>(M*N);
-			for (int i=0;i<M*N;++i) (*pmatrix)[i]=matrix[i];
+			for(int i=0;i<M*N;++i) (*pmatrix)[i]=matrix[i];
 		}
 		xDelete<IssmPDouble>(matrix);
@@ -793,5 +890,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(char***   pstrings,int* pnumstrings,int data_enum){{{*/
+/*FUNCTION IoModel::FetchData(char***       pstrings,int* pnumstrings,int data_enum){{{*/
 void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
 
@@ -1033,17 +1130,206 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchDataToInput{{{*/
-void IoModel::FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum,IssmDouble default_value){
+/*FUNCTION IoModel::FetchMultipleData(char***       pstrings,int* pnumstrings,int data_enum){{{*/
+void  IoModel::FetchMultipleData(char*** pstrings,int* pnumstrings,int data_enum){
+
+	int  num_instances;
+
+	/*output: */
+	int    numstrings = 0;
+	char **strings    = NULL;
+
+	/*intermediary: */
+	char   *string         = NULL;
+	int     string_size;
+	int    *codes          = NULL;
+	int    *code           = NULL;
+	fpos_t *file_positions = NULL;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+		strings=xNew<char*>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				/*check we are indeed finding a string, not something else: */
+				if(codes[i]!=4)_error_("expecting a string for enum " << EnumToStringx(data_enum));
+		
+				/*We have to read a string from disk. First read the dimensions of the string, then the string: */
+				fsetpos(fid,file_positions+i);
+				if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
+			}
+
+			ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			/*Now allocate string: */
+			if(string_size){
+				string=xNew<char>((string_size+1));
+				string[string_size]='\0';
+
+				/*Read string on node 0, then broadcast: */
+				if(my_rank==0){
+					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
+				}
+				ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+			}
+			else{
+				string=xNew<char>(1);
+				string[0]='\0';
+			}
+			strings[i]=string;
+		}
+	}
+	/*Free ressources:*/
+	xDelete<int>(codes);
+	xDelete<fpos_t>(file_positions);
+	
+	/*Assign output pointers: */
+	*pstrings=strings;
+	*pnumstrings=num_instances;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{*/
+void  IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+
+	int     num_instances;
+	fpos_t* file_positions=NULL;
+
+	/*output: */
+	IssmDouble **matrices = NULL;
+	int         *mdims    = NULL;
+	int         *ndims    = NULL;
+
+	/*intermediary: */
+	int          M, N;
+	IssmPDouble *pmatrix = NULL;
+	IssmDouble  *matrix  = NULL;
+	int         *codes   = NULL;
+	int          code;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+	
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+
+		/*Allocate matrices :*/
+		matrices=xNew<IssmDouble*>(num_instances);
+		mdims=xNew<int>(num_instances);
+		ndims=xNew<int>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				code=codes[i];
+
+				if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+
+				/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+				/*numberofelements: */
+				fsetpos(fid,file_positions+i);
+				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+			}
+			ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+			}
+			ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+
+			/*Now allocate matrix: */
+			if(M*N){
+				pmatrix=xNew<IssmPDouble>(M*N);
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(pmatrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+				}
+				ISSM_MPI_Bcast(pmatrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+				_assert_(this->independents);
+				if(this->independents[data_enum]){
+					/*this data has already been checked out! So cancel all that we've done here, and return 
+					 * the data[data_enum] directly: */
+					matrix=this->data[data_enum];
+				}
+				else{
+					matrix=xNew<IssmDouble>(M*N);
+					for (int i=0;i<M*N;++i) matrix[i]=pmatrix[i];
+				}
+				xDelete<IssmPDouble>(pmatrix);
+			}
+			else
+				matrix=NULL;
+			
+			
+			/*Assign: */
+			mdims[i]=M;
+			matrices[i]=matrix;
+			ndims[i]=N;
+		}
+	}
+			
+	/*Free ressources:*/
+	xDelete<fpos_t>(file_positions);
+	xDelete<int>(codes);
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	if(pmdims){
+		*pmdims=mdims;
+	}
+	else{
+		xDelete<int>(mdims);
+	}
+	if(pndims){
+		*pndims=ndims;
+	}
+	else{
+		xDelete<int>(ndims);
+	}
+	*pnumrecords=num_instances;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){{{*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){
+
+	/*intermediary: */
+	int         code,vector_layout;
+	IssmDouble *doublearray = NULL;
+	int         M,N;
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	this->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	/*Defaulting only supported for double arrays*/
+	if(code!=7) _error_(EnumToStringx(vector_enum)<<" is not a double array");
+
+	this->FetchData(&doublearray,&M,&N,vector_enum);
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		if(!doublearray) element->InputUpdateFromConstant(default_value,vector_enum); 
+		else             element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+	}
+
+	/*Free ressources. Pay attention to not freeing an AD mode independent variable though!:*/
+	if(!this->independents[vector_enum]) xDelete<IssmDouble>(doublearray);
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchDataToInput(Elements* elements,int vector_enum){{{*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum){
 
 	/*intermediary: */
 	int     i;
-	bool    defaulting    = false;
-	bool    transient     = false;
-
-	FILE   *fid           = NULL;
-	int     code          = 0;
-	int     vector_layout = 0;
-	int     counter;
-	int     numberofelements;
+	int     code,vector_layout;
 
 	/*variables being fetched: */
@@ -1052,175 +1338,62 @@
 	IssmDouble  scalar;
 	char       *string           = NULL;
-	IssmDouble *IssmDoublevector = NULL;
+	IssmDouble *doublearray = 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);
+	this->SetFilePointerToData(&code, &vector_layout,vector_enum);
 
 	switch(code){
-		case 1: //boolean constant.  {{{
+		case 1: //boolean constant
 			this->FetchData(&boolean,vector_enum);
-
-			/*Add boolean constant input to all elements: */
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					element->InputCreate((IssmDouble)boolean,vector_enum,code);
-					counter++;
-				}
-			}
-			break; /*}}}*/
-		case 2: //integer constant.  {{{
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(boolean,vector_enum);
+			}
+			break;
+		case 2: //integer constant
 			this->FetchData(&integer,vector_enum);
-
-			/*Add integer constant input to all elements: */
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					element->InputCreate((IssmDouble)integer,vector_enum,code);
-					counter++;
-				}
-			}
-			break; /*}}}*/
-		case 3: //IssmDouble constant.  {{{
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(integer,vector_enum);
+			}
+			break;
+		case 3: //IssmDouble constant
 			this->FetchData(&scalar,vector_enum);
-
-			/*Add IssmDouble constant input to all elements: */
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					element->InputCreate(scalar,vector_enum,code); 
-					counter++;
-				}
-			}
-			break; /*}}}*/
-		case 5: //boolean vector.  {{{
-
-			/*Fetch vector:*/
-			this->FetchData(&IssmDoublevector,&M,&N,vector_enum); //we still have a IssmDoublevector, because it might include times in transient mode
-			/*Check we got something, otherwise fetch default: */
-			if(IssmDoublevector){
-				defaulting=false;  //we are not defaulting, because  we do have a vector
-			}
-			else{
-				/*do we have a default enum to go fetch? */
-				if(default_vector_enum!=NoneEnum){
-					/*yes. fetch it: */
-					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
-					if(IssmDoublevector){
-						defaulting=false;  //we are not defaulting, because  we do have a vector
-					}
-					else{
-						/*even the default vector is non existent. we are defaulting to the default value: */
-						defaulting=true;
-					}
-				}
-				else{
-					/*we are left with the default value: */
-					defaulting=true;
-				}
-			}
-
-			/*Create inputs:*/
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
-					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
-					counter++;
-				}
-			}
-			break; /*}}}*/
-		case 6: //int vector{{{
-
-			/*Fetch vector:*/
-			this->FetchData(&IssmDoublevector,&M,&N,vector_enum); //we still have a IssmDoublevector, because it might include times in transient mode
-			/*Check we got something, otherwise fetch default: */
-			if(IssmDoublevector){
-				defaulting=false;  //we are not defaulting, because  we do have a vector
-			}
-			else{
-				/*do we have a default enum to go fetch? */
-				if(default_vector_enum!=NoneEnum){
-					/*yes. fetch it: */
-					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
-					if(IssmDoublevector){
-						defaulting=false;  //we are not defaulting, because  we do have a vector
-					}
-					else{
-						/*even the default vector is non existent. we are defaulting to the default value: */
-						defaulting=true;
-					}
-				}
-				else{
-					/*we are left with the default value: */
-					defaulting=true;
-				}
-			}
-
-			/*Create inputs:*/
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
-					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
-					counter++;
-				}
-			}
-			break; /*}}}*/
-		case 7: //IssmDouble vector{{{
-
-			/*Fetch vector:*/
-			this->FetchData(&IssmDoublevector,&M,&N,vector_enum);
-			/*Check we got something, otherwise fetch default: */
-			if(IssmDoublevector){
-				defaulting=false;  //we are not defaulting, because  we do have a vector
-			}
-			else{
-				/*do we have a default enum to go fetch? */
-				if(default_vector_enum!=NoneEnum){
-					/*yes. fetch it: */
-					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
-					if(IssmDoublevector){
-						defaulting=false;  //we are not defaulting, because  we do have a vector
-					}
-					else{
-						/*even the default vector is non existent. we are defaulting to the default value: */
-						defaulting=true;
-					}
-				}
-				else{
-					/*we are left with the default value: */
-					defaulting=true;
-				}
-			}
-
-			/*Create inputs:*/
-			counter=0;
-			for (i=0;i<numberofelements;i++){
-				if(this->my_elements[i]){
-					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
-					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
-					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
-					counter++;
-				}
-			}
-
-			break; /*}}}*/
-		default: /*{{{*/
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(scalar,vector_enum);
+			}
+			break; 
+		case 5: //boolean vector
+			this->FetchData(&doublearray,&M,&N,vector_enum); //we still have a doublearray, because it might include times in transient mode
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		case 6: //int vector
+			this->FetchData(&doublearray,&M,&N,vector_enum); //we still have a doublearray, because it might include times in transient mode
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		case 7: //IssmDouble vector
+			this->FetchData(&doublearray,&M,&N,vector_enum);
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		default:
 			_error_("data code " << code << " not supported yet!");
 			break;
-			/*}}}*/
 	}
 	/*Free ressources. Pay attention to not freeing an AD mode independent variable though!:*/
-	if (!this->independents[vector_enum] && !this->independents[default_vector_enum]) xDelete<IssmDouble>(IssmDoublevector);
+	if (!this->independents[vector_enum]) xDelete<IssmDouble>(doublearray);
 	xDelete<char>(string);
 }
@@ -1319,5 +1492,4 @@
 	ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 	ISSM_MPI_Bcast(&vector_type,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
-	if(record_code==5) ISSM_MPI_Bcast(&vector_type,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers:*/
@@ -1328,2 +1500,106 @@
 }
 /*}}}*/
+/*FUNCTION IoModel::SetFilePointersToData{{{*/
+fpos_t* IoModel::SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum){
+
+	int     found          = 0;
+	int     record_enum;
+	int     record_length;
+	int     record_code;           //1 to 7 number
+	int     vector_type;           //1 to 7 number
+	int    *vector_types   = NULL;
+	int    *codes          = NULL;
+	int     num_instances  = 0;
+	int     counter;
+	fpos_t *file_positions = NULL;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Go find in the binary file, the data we want to fetch and count the number of 
+	 * instances it appears: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum) num_instances++;
+
+			/*Read the record length, and use it to skip the record: */
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			fseek(fid,record_length,SEEK_CUR);
+		}
+
+		/*Ok, initialize the number of file handles we are going to return: */
+		if(num_instances){
+			file_positions = xNew<fpos_t>(num_instances);
+			codes          = xNew<int>(num_instances);
+			vector_types   = xNew<int>(num_instances);
+		}
+	
+		/*Reset FILE* position to the beginning of the file, and start again, this time saving the data information 
+		 * as we find it: */
+		counter=0;
+		fseek(fid,0,SEEK_SET);
+
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum){
+				/*Ok, we have found the correct string. Pass the record length, and read data type code: */
+				fseek(fid,sizeof(int),SEEK_CUR);
+				if(fread(&record_code,sizeof(int),1,fid)!=1) _error_("Could not read record_code");
+
+				/*if record_code points to a vector, get its type (nodal or elementary): */
+				if(5<=record_code && record_code<=7){
+					if(fread(&vector_type,sizeof(int),1,fid)!=1) _error_("Could not read vector_type");
+				}
+				codes[counter]        = record_code;
+				vector_types[counter] = vector_type;
+				fgetpos(fid,file_positions+counter);
+				
+				/*backup and skip over the record, as we have more work to do: */
+				if(5<=record_code && record_code<=7) fseek(fid,-sizeof(int),SEEK_CUR);
+				fseek(fid,-sizeof(int),SEEK_CUR);
+				fseek(fid,-sizeof(int),SEEK_CUR);
+				
+				/*increment counter: */
+				counter++;
+			}
+
+			/*Read the record length, and use it to skip this record, as it has already been processed: */
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			/*skip: */
+			fseek(fid,record_length,SEEK_CUR);
+		}
+	}
+
+	/*Broadcast data: */
+	ISSM_MPI_Bcast(&num_instances,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pcodes         = codes;
+	*pnum_instances = num_instances;
+	if(pvector_types){
+		*pvector_types=vector_types;
+	}
+	else{
+		xDelete<int>(vector_types);
+	}
+	return file_positions;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 16559)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 16560)
@@ -31,15 +31,15 @@
 
 		/*Mesh properties and connectivity tables*/
-		int   dim;
-		int   numberofvertices;
-		int   numberofelements;
-		int   numberoffaces;
-		int   numberofedges;
-		int  *elements;
-		int  *faces;
-		int  *edges;
-		int  *elementtoedgeconnectivity;
-		int  *singlenodetoelementconnectivity;
-		int  *numbernodetoelementconnectivity;
+		int  meshtype;
+		int  numberofvertices;
+		int  numberofelements;
+		int  numberoffaces;
+		int  numberofedges;
+		int *elements;
+		int *faces;
+		int *edges;
+		int *elementtoedgeconnectivity;
+		int *singlenodetoelementconnectivity;
+		int *numbernodetoelementconnectivity;
 
 		/*Data to synchronize through low level object drivers: */
@@ -67,4 +67,5 @@
 		void        DeleteData(int num,...);
 		void        DeleteData(IssmDouble* vector, int dataenum);
+		void        DeleteData(char*** pstringarray, int numstrings, int dataenum);
 		void        FetchConstants(void);
 		void        FetchData(bool* pboolean,int data_enum);
@@ -76,10 +77,15 @@
 		void        FetchData(char***   pstringarray,int* pnumstrings,int data_enum);
 		void        FetchData(IssmDouble*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		void        FetchMultipleData(char***   pstringarray,int* pnumstrings,int data_enum);
+		void        FetchMultipleData(IssmDouble*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
 		void        FetchData(Option **poption,int data_enum);
 		void        FetchData(int num,...);
-		void        FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum=NoneEnum,IssmDouble default_value=0.);
+		void        FetchDataToInput(Elements* elements,int vector_enum);
+		void        FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value);
 		void        LastIndex(int *pindex);
 		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
+		fpos_t*     SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum);
 		void        DeclareIndependents(void);
+		void        StartTrace(void);
 		void        FetchIndependent(int dependent_enum);
 };
Index: /issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 16560)
@@ -91,5 +91,9 @@
 	if (Neff<0)Neff=0;
 
-	if(strcmp(element_type,"2d")==0){
+	if(strcmp(element_type,"1d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		vmag=sqrt(vx*vx);
+	}
+	else if(strcmp(element_type,"2d")==0){
 		this->GetInputValue(&vx, gauss,vxenum);
 		this->GetInputValue(&vy, gauss,vyenum);
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 16560)
@@ -39,15 +39,10 @@
 	int  pos1,pos2,pos3,pos4;
 	int  num_nodes;
-	int  num_elems;
 
 	/*numericalflux constructor data: */
 	int   numericalflux_elem_ids[2];
-	int   numericalflux_mparid;
 	int   numericalflux_vertex_ids[2];
 	int   numericalflux_node_ids[4];
 	int   numericalflux_type;
-
-	/* Get MatPar id */
-	numericalflux_mparid=iomodel->numberofelements+1; //matlab indexing
 
 	/*Get edge*/
@@ -60,5 +55,5 @@
 	if(e2==-1){
 		/* Boundary edge, only one element */
-		num_elems=1; num_nodes=2;
+		num_nodes=2;
 		numericalflux_type=BoundaryEnum;
 		numericalflux_elem_ids[0]=e1;
@@ -66,5 +61,5 @@
 	else{
 		/* internal edge: connected to 2 elements */
-		num_elems=2; num_nodes=4;
+		 num_nodes=4;
 		numericalflux_type=InternalEnum;
 		numericalflux_elem_ids[0]=e1;
Index: /issm/trunk/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 16560)
@@ -241,4 +241,9 @@
 		case HydrologyDCInefficientAnalysisEnum:
 			Ke=PenaltyCreateKMatrixHydrologyDCInefficient(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_DAMAGE_
+		case DamageEvolutionAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDamageEvolution(kmax);
 			break;
 		#endif
@@ -278,4 +283,10 @@
 			break;
 		#endif
+		#ifdef _HAVE_DAMAGE_
+		case DamageEvolutionAnalysisEnum:
+			pe=PenaltyCreatePVectorDamageEvolution(kmax);
+			break;
+		#endif
+
 		default:
 			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
@@ -430,4 +441,11 @@
 	}
 	#endif
+	#ifdef _HAVE_DAMAGE_
+	else if (analysis_type==DamageEvolutionAnalysisEnum){
+		ConstraintActivateDamageEvolution(punstable);
+		return;
+	}
+	#endif
+
 	else{
 		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
@@ -441,7 +459,4 @@
 
 	//   The penalty is stable if it doesn't change during to successive iterations.   
-
-	int        found=0;
-	const int  numnodes=1;
 	IssmDouble pressure;
 	IssmDouble temperature;
@@ -449,5 +464,4 @@
 	int        new_active;
 	int        unstable=0;
-	int        reset_penalties=0;
 	int        penalty_lock;
 
@@ -508,5 +522,4 @@
 ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){
 
-	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble pressure,temperature,t_pmp;
 	IssmDouble penalty_factor;
@@ -538,5 +551,4 @@
 ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){
 
-	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble    penalty_factor;
 
@@ -557,5 +569,4 @@
 ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){
 
-	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble pressure;
 	IssmDouble temperature;
@@ -600,5 +611,4 @@
 ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){
 
-	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble pressure;
 	IssmDouble t_pmp;
@@ -630,9 +640,5 @@
 
 	//   The penalty is stable if it doesn't change during two consecutive iterations.   
-	const int  numnodes        = 1;
 	int        unstable        = 0;
-	int        reset_penalties = 0;
-	int        found           = 0;	
-	int        penalty_lock;
 	int        new_active;
 	IssmDouble pressure;
@@ -670,5 +676,4 @@
 ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){
 
-	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble    penalty_factor;
 
@@ -689,5 +694,4 @@
 ElementVector* Pengrid::PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax){
 
-	const int  numdof=NUMVERTICES*NDOF1;
 	IssmDouble h_max;
 	IssmDouble penalty_factor;
@@ -709,13 +713,109 @@
 /*}}}*/
 #endif
+#ifdef _HAVE_DAMAGE_
+/*FUNCTION Pengrid::ConstraintActivateDamageEvolution {{{*/
+void  Pengrid::ConstraintActivateDamageEvolution(int* punstable){
+
+	//   The penalty is stable if it doesn't change during to successive iterations.   
+	IssmDouble max_damage;
+	IssmDouble damage;
+	int        new_active;
+	int        unstable=0;
+	int        penalty_lock;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	//First recover damage  using the element: */
+	element->GetMaterialInputValue(&damage,node,DamageDbarEnum);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_lock,DamagePenaltyLockEnum);
+	parameters->FindParam(&max_damage,DamageMaxDamageEnum);
+	
+	//Figure out if damage>max_damage, in which case, this penalty needs to be activated.
+	//Would need to do the same for damage<0 if penalties are used.  For now, ConstraintStatex 
+	//is not called in solutionsequence_damage_nonlinear, so no penalties are applied.
+
+	if (damage>max_damage){
+		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 penalty_lock times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+
+	//Set penalty flag
+	active=new_active;
+
+	//*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixDamageEvolution {{{*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixDamageEvolution(IssmDouble kmax){
+
+	IssmDouble    penalty_factor;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,DamagePenaltyFactorEnum);
+
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorDamageEvolution {{{*/
+ElementVector* Pengrid::PenaltyCreatePVectorDamageEvolution(IssmDouble kmax){
+
+	IssmDouble penalty_factor;
+	IssmDouble max_damage;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_factor,DamagePenaltyFactorEnum);
+	parameters->FindParam(&max_damage,DamageMaxDamageEnum);
+
+	//right hand side penalizes to max_damage
+	pe->values[0]=kmax*pow(10.,penalty_factor)*max_damage;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
 /*FUNCTION Pengrid::ResetConstraint {{{*/
 void  Pengrid::ResetConstraint(void){
-	active=0;
-	zigzag_counter=0;
-}
-/*}}}*/
-/*FUNCTION Pengrid::UpdateInputs {{{*/
-void  Pengrid::UpdateInputs(IssmDouble* solution){
-	_error_("not supported yet!");
-}
-/*}}}*/
+	active         = 0;
+	zigzag_counter = 0;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 16560)
@@ -91,4 +91,10 @@
 		void           ConstraintActivateThermal(int* punstable);
 		#endif
+		#ifdef _HAVE_DAMAGE_
+		ElementMatrix* PenaltyCreateKMatrixDamageEvolution(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorDamageEvolution(IssmDouble kmax);
+		void           ConstraintActivateDamageEvolution(int* punstable);
+		#endif
+
 		#ifdef _HAVE_HYDROLOGY_
 		ElementMatrix* PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax);
@@ -97,5 +103,4 @@
 		#endif
 		void  ConstraintActivate(int* punstable);
-		void  UpdateInputs(IssmDouble* solution);
 		void  ResetConstraint(void);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 16560)
@@ -36,4 +36,5 @@
 
 	/*data: */
+	const int RIFTINFOSIZE = 12;
 	int    riftfront_node_ids[2];
 	int    riftfront_elem_ids[2];
@@ -454,5 +455,4 @@
 
 	const int   numdof = NDOF2*NUMVERTICES;
-	int         dofs[1]             = {0};
 	IssmDouble  thickness;
 	IssmDouble  h[2];
@@ -534,5 +534,4 @@
 ElementVector* Riftfront::PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax){
 
-	const int  numdof = NDOF2*NUMVERTICES;
 	int        j;
 	IssmDouble rho_ice;
@@ -636,17 +635,16 @@
 int Riftfront::Constrain(int* punstable){
 
-	const int   numnodes        = 2;
-	IssmDouble      penetration;
+	IssmDouble  penetration;
 	int         activate;
 	int         unstable;
-	IssmDouble      vx1;
-	IssmDouble      vy1;
-	IssmDouble      vx2;
-	IssmDouble      vy2;
-	IssmDouble      fractionincrement;
+	IssmDouble  vx1;
+	IssmDouble  vy1;
+	IssmDouble  vx2;
+	IssmDouble  vy2;
+	IssmDouble  fractionincrement;
 
 	/*Objects: */
-	Tria       *tria1           = NULL;
-	Tria       *tria2           = NULL;
+	Tria  *tria1 = NULL;
+	Tria  *tria2 = NULL;
 
 	/*enum of element? */
@@ -736,226 +734,4 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::IsMaterialStable {{{*/
-int   Riftfront::IsMaterialStable(void){
-
-	IssmDouble converged=0;
-
-	this->inputs->GetInputValue(&converged,ConvergedEnum);
-
-	if(reCast<int,IssmDouble>(converged)){
-		/*ok, material non-linearity has converged. If that was already the case, we keep 
-		 * constraining the rift front. If it was not, and this is the first time the material 
-		 * has converged, we start constraining now!: */
-		this->material_converged=1;
-	}
-
-	return this->material_converged;
-}
-/*}}}*/
-/*FUNCTION Riftfront::MaxPenetration {{{*/
-int   Riftfront::MaxPenetration(IssmDouble* ppenetration){
-
-	const int     numnodes=2;
-	IssmDouble        penetration=0;
-	IssmDouble      vx1;
-	IssmDouble      vy1;
-	IssmDouble      vx2;
-	IssmDouble      vy2;
-
-	/*Objects: */
-	Tria       *tria1           = NULL;
-	Tria       *tria2           = NULL;
-
-	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
-
-	/*recover elements on both side of rift: */
-	tria1=(Tria*)elements[0];
-	tria2=(Tria*)elements[1];
-
-	//initialize: 
-	penetration=-1;
-
-	/*recover velocity: */
-	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
-	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
-	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
-	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
-
-	/*Node1 faces node2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
-	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
-
-	/*Now, we return penetration only if we are active!: */
-	if(this->active==0)penetration=-1;
-
-	/*If we are zigzag locked, same thing: */
-	if(this->counter>this->penalty_lock)penetration=-1;
-
-	/*assign output pointer: */
-	*ppenetration=penetration;
-	return 1;
-}
-/*}}}*/
-/*FUNCTION Riftfront::Penetration {{{*/
-int   Riftfront::Penetration(IssmDouble* ppenetration){
-
-	IssmDouble    vx1;
-	IssmDouble    vy1;
-	IssmDouble    vx2;
-	IssmDouble    vy2;
-
-	IssmDouble    penetration;
-
-	/*Objects: */
-	Tria     *tria1       = NULL;
-	Tria     *tria2       = NULL;
-
-	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
-
-	/*recover elements on both side of rift: */
-	tria1=(Tria*)elements[0];
-	tria2=(Tria*)elements[1];
-
-	/*First recover velocity: */
-	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
-	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
-	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
-	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
-
-	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
-	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
-
-	/*Now, we return penetration only if we are active!: */
-	if(this->active==0)penetration=0;
-
-	/*assign output pointer: */
-	*ppenetration=penetration;
-	return 1;
-}
-/*}}}*/
-/*FUNCTION Riftfront::PotentialUnstableConstraint {{{*/
-int   Riftfront::PotentialUnstableConstraint(int* punstable){
-
-	const int   numnodes        = 2;
-	IssmDouble  penetration;
-	int         unstable;
-	IssmDouble  vx1;
-	IssmDouble  vy1;
-	IssmDouble  vx2;
-	IssmDouble  vy2;
-
-	/*Objects: */
-	Tria       *tria1 = NULL;
-	Tria       *tria2 = NULL;
-
-	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
-
-	/*recover elements on both side of rift: */
-	tria1=(Tria*)elements[0];
-	tria2=(Tria*)elements[1];
-
-	/*First recover velocity: */
-	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
-	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
-	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
-	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
-
-	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
-	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
-
-	/*Ok, we are looking for positive penetration in an active constraint: */
-	if(this->active){
-		if (penetration>=0){
-			unstable=1;
-		}
-		else{
-			unstable=0;
-		}
-	}
-	else{
-		unstable=0;
-	}
-
-	/*assign output pointer: */
-	*punstable=unstable;
-	return 1;
-}
-/*}}}*/
-/*FUNCTION Riftfront::PreConstrain {{{*/
-int   Riftfront::PreConstrain(int* punstable){
-
-	const int   numnodes    = 2;
-	IssmDouble      penetration;
-	int         unstable;
-	IssmDouble      vx1;
-	IssmDouble      vy1;
-	IssmDouble      vx2;
-	IssmDouble      vy2;
-
-	/*Objects: */
-	Tria       *tria1       = NULL;
-	Tria       *tria2       = NULL;
-
-	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
-
-	/*recover elements on both side of rift: */
-	tria1=(Tria*)elements[0];
-	tria2=(Tria*)elements[1];
-
-	/*First recover velocity: */
-	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
-	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
-	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
-	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
-
-	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
-	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
-
-	/*Ok, we are preconstraining here. Ie, anything that penetrates is constrained until stability of the entire set 
-	 * of constraints is reached.: */
-	if(penetration<0){
-		if (!this->active){
-			/*This is the first time penetration happens: */
-			this->active=1;
-			unstable=1;
-		}
-		else{
-			/*This constraint was already active: */
-			this->active=1;
-			unstable=0;
-		}
-	}
-	else{
-		/*No penetration happening. : */
-		if (!this->active){
-			/*This penalty was not active, and no penetration happening. Do nonthing: */
-			this->active=0;
-			unstable=0; 
-		}
-		else{
-			/*Ok, this penalty wants to get released. But not now, this is preconstraint, not constraint: */
-			this->active=1;
-			unstable=0;
-		}
-	}
-
-	/*assign output pointer: */
-	*punstable=unstable;
-	return 1;
-}
-/*}}}*/
-/*FUNCTION Riftfront::PreStable {{{*/
-bool  Riftfront::PreStable(){
-	return prestable;
-}
-/*}}}*/
-/*FUNCTION Riftfront::SetPreStable {{{*/
-void Riftfront::SetPreStable(){
-	prestable=1;
-}
-/*}}}*/
 /*FUNCTION Riftfront::IsInput{{{*/
 bool Riftfront::IsInput(int name){
Index: /issm/trunk/src/c/classes/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 16560)
@@ -85,19 +85,11 @@
 		/*}}}*/
 		/*Riftfront specific routines: {{{*/
-		bool  PreStable();
 		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
 		ElementVector* PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax);
-		void  SetPreStable();
-		int   PreConstrain(int* punstable);
 		int   Constrain(int* punstable);
 		void  FreezeConstraints(void);
 		bool  IsFrozen(void);
-		int   Penetration(IssmDouble* ppenetration);
-		int   MaxPenetration(IssmDouble* ppenetration);
-		int   PotentialUnstableConstraint(int* punstable);
-		int   IsMaterialStable(void);
 		bool  IsInput(int name);
 		/*}}}*/
 };
-
 #endif  /* _RIFTFRONT_H_ */
Index: /issm/trunk/src/c/classes/Massfluxatgate.h
===================================================================
--- /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 16560)
+++ /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 16560)
@@ -0,0 +1,165 @@
+/*!\file Massfluxatgate.h
+ * \brief: header file for Massfluxatgate object
+ */
+
+#ifndef _MASSFLUXATGATE_H_
+#define _MASSFLUXATGATE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+/*}}}*/
+
+template <class doubletype> 
+class Massfluxatgate: public Object, public Definition{
+
+	public: 
+
+		char*       name;
+		int         numsegments;
+		doubletype *x1;
+		doubletype *y1;
+		doubletype *x2;
+		doubletype *y2;
+		int*        elements;
+
+		/*Massfluxatgate constructors, destructors :*/
+		/*FUNCTION Massfluxatgate() {{{*/
+		Massfluxatgate(){
+			this->name     = 0;
+			this->numsegments     = 0;
+			this->segments   = 0;
+		}
+		/*}}}*/
+		/*FUNCTION Massfluxatgate(char* name, int numsegments, doubletype* segments) {{{*/
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_segments) {
+			
+			int i;
+
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->numsegments=in_numsegments;
+
+			if(this->numsegments){
+				this->x1=xNew<doubletype>(this->numsegments);
+				this->x2=xNew<doubletype>(this->numsegments);
+				this->y1=xNew<doubletype>(this->numsegments);
+				this->y2=xNew<doubletype>(this->numsegments);
+				this->elements=xNew<int>(this->numsegments);
+
+				for(i=0;i<this->numsegments;i++){
+					this->x1[i]=in_segments[5*i+0];
+					this->y1[i]=in_segments[5*i+1];
+					this->x2[i]=in_segments[5*i+2];
+					this->y2[i]=in_segments[5*i+3];
+					this->elements[i]=reCast<int,doubletype>(in_segments[5*i+4]);
+				}
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Massfluxatgate(char* name, int numsegments, doubletype* x1, doubletype* y1, doubletype* x2, doubletype* y2,int* elements) {{{*/
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){
+
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->numsegments=in_numsegments;
+
+			if(this->numsegments){
+				this->x1=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->x1,in_x1,this->numsegments);
+				this->y1=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->y1,in_y1,this->numsegments);
+				this->x2=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->x2,in_x2,this->numsegments);
+				this->y2=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->y2,in_y2,this->numsegments);
+				this->elements=xNew<int>(this->numsegments); xMemCpy<int>(this->elements,in_elements,this->numsegments);
+				
+			}
+		}
+		/*}}}*/
+		/*FUNCTION ~Massfluxatgate() {{{*/
+		~Massfluxatgate(){
+			xDelete<doubletype>(this->x1);
+			xDelete<doubletype>(this->y1);
+			xDelete<doubletype>(this->x2);
+			xDelete<doubletype>(this->y2);
+			xDelete<int>(this->elements);
+			xDelete<char>(this->name);
+		}
+		/*}}}*/
+
+		/*Object virtual function resolutoin: */
+		/*FUNCTION Echo(){{{*/
+		void Echo(void){
+			_printf_(" Massfluxatgate: " << name << "\n");
+			_printf_("    numsegments: " << numsegments << "\n");
+			if(numsegments){
+				_printf_("   element: x1, y1, x2, y2:\n");
+				for(int i=0;i<numsegments;i++){
+					_printf_(elements[i] << " " << x1[i] << " " << y1[i] << " " << x2[i] << " " << y2[i] << "\n");
+				}
+			}
+		}
+		/*}}}*/
+		/*FUNCTION DeepEcho(){{{*/
+		void DeepEcho(void){
+			this->Echo();
+		}
+		/*}}}*/
+		/*FUNCTION Id(){{{*/
+		int Id(void){
+			return -1;
+		}
+		/*}}}*/
+		/*FUNCTION ObjectEnum{{{*/
+		int ObjectEnum(void){
+			return MassfluxatgateEnum;
+		}
+		/*}}}*/
+		/*FUNCTION copy {{{*/
+		Object* copy() {
+			return new Massfluxatgate(this->name,this->numsegments,this->x1,this->y1,this->x2,this->y2,this->elements); 
+		}
+		/*}}}*/
+		/*Definition virtual function resolutoin: */
+		/*FUNCTION char* Name() {{{*/
+		char* Name(){
+
+			char* name2=xNew<char>(strlen(this->name)+1);
+			xMemCpy(name2,this->name,strlen(this->name)+1);
+
+			return name2;
+		}
+		/*}}}*/
+		/*FUNCTION doubletype* Response(FemModel* femmodel) {{{*/
+		 IssmDouble Response(FemModel* femmodel){
+
+			int          i,j;
+			Element     *element       = NULL;
+			IssmDouble mass_flux     = 0;
+			IssmDouble all_mass_flux = 0;
+
+			/*Go through segments, and then elements, and figure out which elements belong to a segment. 
+			 * When we find one, use the element to compute the mass flux on the segment: */
+			for(i=0;i<numsegments;i++){
+				for(j=0;j<femmodel->elements->Size();j++){
+					element=(Element*)femmodel->elements->GetObjectByOffset(j);
+					if (element->Id()==this->elements[i]){
+						/*We found the element which owns this segment, use it to compute the mass flux: */
+						mass_flux+=element->MassFlux(x1[i],y1[i],x2[i],y2[i],elements[i]);
+						break;
+					}
+				}
+			}
+
+			ISSM_MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+			mass_flux=all_mass_flux;
+			return mass_flux;
+		}
+			/*}}}*/
+};
+
+#endif  /* _MASSFLUXATGATE_H_ */
Index: sm/trunk/src/c/classes/Materials/Matdamageice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matdamageice.cpp	(revision 16559)
+++ 	(revision )
@@ -1,894 +1,0 @@
-/*!\file Matdamageice.c
- * \brief: implementation of the Matdamageice object
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../classes.h"
-#include "shared/shared.h"
-
-/*Matdamageice constructors and destructor*/
-/*FUNCTION Matdamageice::Matdamageice(){{{*/
-Matdamageice::Matdamageice(){
-	this->inputs=NULL;
-	this->helement=NULL;
-	return;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::Matdamageice(int id, int index, IoModel* iomodel, int num_vertices){{{*/
-Matdamageice::Matdamageice(int matice_mid,int index, IoModel* iomodel){
-
-	/*Intermediaries:*/
-	int    matice_eid;
-
-	/*Initialize id*/
-	this->mid=matice_mid;
-
-	/*Initialize inputs*/
-	this->inputs=new Inputs();
-
-	/*Initialize inputs from IoModel*/
-	this->InputUpdateFromIoModel(index,iomodel);
-
-	/*Hooks: */
-	matice_eid=index+1;
-	this->helement=new Hook(&matice_eid,1);
-
-	return;
-
-}
-/*}}}*/
-/*FUNCTION Matdamageice::~Matdamageice(){{{*/
-Matdamageice::~Matdamageice(){
-	delete helement;
-	delete inputs;
-	return;
-}
-/*}}}*/
-
-/*Object virtual functions definitions:*/
-/*FUNCTION Matdamageice::Echo {{{*/
-void Matdamageice::Echo(void){
-
-	_printf_("Matdamageice:\n");
-	_printf_("   mid: " << mid << "\n");
-	_printf_("   inputs:\n");
-	inputs->Echo();
-	_printf_("   element:\n");
-	helement->Echo();
-}
-/*}}}*/
-/*FUNCTION Matdamageice::DeepEcho {{{*/
-void Matdamageice::DeepEcho(void){
-
-	_printf_("Matdamageice:\n");
-	_printf_("   mid: " << mid << "\n");
-	_printf_("   inputs:\n");
-	inputs->DeepEcho();
-	_printf_("   element:\n");
-	helement->Echo();
-}		
-/*}}}*/
-/*FUNCTION Matdamageice::Id {{{*/
-int    Matdamageice::Id(void){ return mid; }
-/*}}}*/
-/*FUNCTION Matdamageice::ObjectEnum{{{*/
-int Matdamageice::ObjectEnum(void){
-
-	return MatdamageiceEnum;
-
-}
-/*}}}*/
-/*FUNCTION Matdamageice::copy {{{*/
-Object* Matdamageice::copy() {
-
-	/*Output*/
-	Matdamageice* matice=NULL;
-
-	/*Initialize output*/
-	matice=new Matdamageice();
-
-	/*copy fields: */
-	matice->mid=this->mid;
-	matice->helement=(Hook*)this->helement->copy();
-	if(this->inputs) matice->inputs=(Inputs*)this->inputs->Copy();
-	else  matice->inputs=new Inputs();
-
-	return matice;
-}
-/*}}}*/
-
-/*Matdamageice management*/
-/*FUNCTION Matdamageice::Configure {{{*/
-void  Matdamageice::Configure(Elements* elementsin){
-
-	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
-	 * datasets, using internal ids and offsets hidden in hooks: */
-	helement->configure((DataSet*)elementsin);
-}
-/*}}}*/
-/*FUNCTION Matdamageice::SetCurrentConfiguration {{{*/
-void  Matdamageice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetA {{{*/
-IssmDouble Matdamageice::GetA(){
-	/*
-	 * A = 1/B^n
-	 */
-
-	IssmDouble B,n;
-
-	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
-	n=this->GetN();
-
-	return pow(B,-n);
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetB {{{*/
-IssmDouble Matdamageice::GetB(){
-
-	/*Output*/
-	IssmDouble B;
-
-	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
-	return B;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetBbar {{{*/
-IssmDouble Matdamageice::GetBbar(){
-
-	/*Output*/
-	IssmDouble Bbar;
-
-	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
-	return Bbar;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetN {{{*/
-IssmDouble Matdamageice::GetN(){
-
-	/*Output*/
-	IssmDouble n;
-
-	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
-	return n;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetZ {{{*/
-IssmDouble Matdamageice::GetZ(){
-
-	/*Output*/
-	IssmDouble Z;
-
-	inputs->GetInputAverage(&Z,MaterialsRheologyZEnum);
-	return Z;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetZbar {{{*/
-IssmDouble Matdamageice::GetZbar(){
-
-	/*Output*/
-	IssmDouble Zbar;
-
-	inputs->GetInputAverage(&Zbar,MaterialsRheologyZbarEnum);
-	return Zbar;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetVectorFromInputs{{{*/
-void  Matdamageice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
-
-	/*Intermediaries*/
-	Element *element= NULL;
-
-	/*Recover element*/
-	element=(Element*)helement->delivers();
-
-	/*Check that input_enum is a material input*/
-	if (!IsInput(input_enum)) return;
-
-	switch(element->ObjectEnum()){
-
-		case TriaEnum:{
-
-			/*Prepare index list*/
-			int vertexpidlist[3];
-			((Tria*)element)->GetVertexPidList(&vertexpidlist[0]);
-
-			/*Get input (either in element or material)*/
-			Input* input=inputs->GetInput(input_enum);
-			if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in material");
-
-			/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
-			input->GetVectorFromInputs(vector,&vertexpidlist[0]);}
-			break;
-
-		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
-	}
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosity2d {{{*/
-void  Matdamageice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
-	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
-												   Z * B
-	  viscosity= -------------------------------------------------------------------
-						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
-
-	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
-	  vector, and n the flow law exponent.
-
-	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
-	  return 10^14, initial viscosity.
-	  */
-
-	/*output: */
-	IssmDouble viscosity;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy;
-
-	/*Intermediary: */
-	IssmDouble A,e;
-	IssmDouble Btmp,B,n,Z;
-
-	/*Get B and n*/
-	Btmp=GetBbar();
-	Z=GetZbar();
-	n=GetN();
-	B=Z*Btmp;
-
-	if (n==1){
-		/*Viscous behaviour! viscosity=B: */
-		viscosity=B/2;
-	}
-	else{
-		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-			viscosity=0.5*pow(10.,14);
-		}
-		else{
-			/*Retrive strain rate components: */
-			exx=*(epsilon+0);
-			eyy=*(epsilon+1);
-			exy=*(epsilon+2);
-
-			/*Build viscosity: viscosity=B/(2*A^e) */
-			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
-			if(A==0){
-				/*Maxiviscositym viscosity for 0 shear areas: */
-				viscosity=2.5*pow(10.,17);
-			}
-			else{
-				e=(n-1)/(2*n);
-				viscosity=B/(2*pow(A,e));
-			}
-		}
-	}
-
-	/*Checks in debugging mode*/
-	if(viscosity<=0) _error_("Negative viscosity");
-	_assert_(B>0);
-	_assert_(n>0);
-
-	/*Return: */
-	*pviscosity=viscosity;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosity3d {{{*/
-void  Matdamageice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
-
-	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
-	 *
-	 *                                               B
-	 * viscosity3d= -------------------------------------------------------------------
-	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
-	 *
-	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
-	 *     vector, and n the flow law exponent.
-	 *
-	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
-	 * return g, initial viscosity.
-	 */
-
-	/*output: */
-	IssmDouble viscosity3d;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy,exz,eyz;
-
-	/*Intermediaries: */
-	IssmDouble A,e;
-	IssmDouble B,n,Z;
-
-	/*Get B, Z and n*/
-	n=GetN();
-	Z=GetZ();
-	B=Z*GetB();
-
-	if (n==1){
-		/*Viscous behaviour! viscosity3d=B: */
-		viscosity3d=B/2;
-	}
-	else{
-		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
-				(epsilon[3]==0) && (epsilon[4]==0)){
-			viscosity3d=0.5*pow(10.,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(10.,17);
-			}
-			else{
-				e=(n-1)/2/n;
-
-				viscosity3d=B/(2*pow(A,e));
-			}
-		}
-	}
-
-	/*Checks in debugging mode*/
-	if(viscosity3d<=0) _error_("Negative viscosity");
-	_assert_(B>0);
-	_assert_(n>0);
-
-	/*Assign output pointers:*/
-	*pviscosity3d=viscosity3d;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosity3dFS {{{*/
-void  Matdamageice::GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
-	 *
-	 *                                          B
-	 * viscosity3d= -------------------------------------------------------------------
-	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
-	 *
-	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
-	 *     vector, and n the flow law exponent.
-	 *
-	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
-	 * return g, initial viscosity.
-	 */
-
-	/*output: */
-	IssmDouble viscosity3d;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy,exz,eyz,ezz;
-
-	/*Intermediaries: */
-	IssmDouble A,e;
-	IssmDouble B,n,Z;
-	IssmDouble eps0;
-
-	/*Get B and n*/
-	eps0=pow(10.,(IssmDouble)-27);
-	n=GetN();
-	Z=GetZ();
-	B=Z*GetB();
-
-	if (n==1){
-		/*Viscous behaviour! viscosity3d=B: */
-		viscosity3d=B/2;
-	}
-	else{
-		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
-				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
-			viscosity3d=0.5*pow(10.,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(10.,17);
-			}
-			else{
-				e=(n-1)/2/n;
-				viscosity3d=B/(2*pow(A,e));
-			}
-		}
-	}
-
-	/*Checks in debugging mode*/
-	if(viscosity3d<=0) _error_("Negative viscosity");
-	_assert_(B>0);
-	_assert_(n>0);
-
-	/*Assign output pointers:*/
-	*pviscosity3d=viscosity3d;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosityComplement {{{*/
-void  Matdamageice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
-	 *
-	 *  										                1
-	 * viscosity= -------------------------------------------------------------------
-	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
-	 *
-	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
-	 * return mu20, initial viscosity.
-	 */
-
-	/*output: */
-	IssmDouble viscosity_complement;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy;
-
-	/*Intermediary value A and exponent e: */
-	IssmDouble A,e;
-	IssmDouble B,n;
-
-	/*Get B and n*/
-	B=GetBbar();
-	n=GetN();
-
-	if(epsilon){
-		exx=*(epsilon+0);
-		eyy=*(epsilon+1);
-		exy=*(epsilon+2);
-
-		/*Build viscosity: mu2=B/(2*A^e) */
-		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
-		if(A==0){
-			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow(10.,17);
-		}
-		else{
-			e=(n-1)/(2*n);
-
-			viscosity_complement=1/(2*pow(A,e));
-		}
-	}
-	else{
-		viscosity_complement=4.5*pow(10.,17);
-	}
-
-	/*Checks in debugging mode*/
-	_assert_(B>0);
-	_assert_(n>0);
-	_assert_(viscosity_complement>0);
-
-	/*Return: */
-	*pviscosity_complement=viscosity_complement;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosityZComplement {{{*/
-void  Matdamageice::GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
-	/*Return viscosity derivative for control method d(mu)/dZ: 
-	 *
-	 *  										               B 
-	 * dviscosity= -------------------------------------------------------------------
-	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
-	 *
-	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
-	 * return mu20, initial viscosity.
-	 */
-
-	/*output: */
-	IssmDouble viscosity_complement;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy;
-
-	/*Intermediary value A and exponent e: */
-	IssmDouble A,e;
-	IssmDouble B,n;
-
-	/*Get B and n*/
-	B=GetBbar();
-	n=GetN();
-
-	if(epsilon){
-		exx=*(epsilon+0);
-		eyy=*(epsilon+1);
-		exy=*(epsilon+2);
-
-		/*Build viscosity: mu2=B/(2*A^e) */
-		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
-		if(A==0){
-			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow(10.,17);
-		}
-		else{
-			e=(n-1)/(2*n);
-
-			viscosity_complement=B/(2*pow(A,e));
-		}
-	}
-	else{
-		viscosity_complement=4.5*pow(10.,17);
-	}
-
-	/*Checks in debugging mode*/
-	_assert_(B>0);
-	_assert_(n>0);
-	_assert_(viscosity_complement>0);
-
-	/*Return: */
-	*pviscosity_complement=viscosity_complement;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosityDerivativeEpsSquare{{{*/
-void  Matdamageice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
-
-	/*output: */
-	IssmDouble mu_prime;
-	IssmDouble mu,n,eff2;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy,exz,eyz;
-
-	/*Get visocisty and n*/
-	GetViscosity3d(&mu,epsilon);
-	n=GetN();
-
-	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
-				(epsilon[3]==0) && (epsilon[4]==0)){
-		mu_prime=0.5*pow(10.,14);
-	}
-	else{
-		/*Retrive strain rate components: */
-		exx=epsilon[0];
-		eyy=epsilon[1];
-		exy=epsilon[2];
-		exz=epsilon[3];
-		eyz=epsilon[4];
-		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
-
-		mu_prime=(1-n)/(2*n) * mu/eff2;
-	}
-
-	/*Assign output pointers:*/
-	*pmu_prime=mu_prime;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosityDerivativeEpsSquareFS{{{*/
-void  Matdamageice::GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* epsilon){
-
-	/*output: */
-	IssmDouble mu_prime;
-	IssmDouble mu,n,eff2;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,ezz,exy,exz,eyz;
-
-	/*Get visocisty and n*/
-	GetViscosity3d(&mu,epsilon);
-	n=GetN();
-
-	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
-				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
-		mu_prime=0.5*pow(10.,14);
-	}
-	else{
-		/*Retrive strain rate components: */
-		exx=epsilon[0];
-		eyy=epsilon[1];
-		ezz=epsilon[2];
-		exy=epsilon[3];
-		exz=epsilon[4];
-		eyz=epsilon[5];
-		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
-
-		mu_prime=(1-n)/(2*n) * mu/eff2;
-	}
-
-	/*Assign output pointers:*/
-	*pmu_prime=mu_prime;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::GetViscosity2dDerivativeEpsSquare{{{*/
-void  Matdamageice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
-
-	/*output: */
-	IssmDouble mu_prime;
-	IssmDouble mu,n,eff2;
-
-	/*input strain rate: */
-	IssmDouble exx,eyy,exy;
-
-	/*Get visocisty and n*/
-	GetViscosity2d(&mu,epsilon);
-	n=GetN();
-
-	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-		mu_prime=0.5*pow(10.,14);
-	}
-	else{
-		/*Retrive strain rate components: */
-		exx=epsilon[0];
-		eyy=epsilon[1];
-		exy=epsilon[2];
-		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy ;
-
-		mu_prime=(1-n)/(2*n) * mu/eff2;
-	}
-
-	/*Assign output pointers:*/
-	*pmu_prime=mu_prime;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputDuplicate{{{*/
-void  Matdamageice::InputDuplicate(int original_enum,int new_enum){
-
-	/*Call inputs method*/
-	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
-
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type){
-
-	/*Intermediaries*/
-	Element *element      = NULL;
-
-	/*Recover element*/
-	element=(Element*)helement->delivers();
-
-	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
-
-	switch(type){
-
-		case VertexEnum:
-
-			switch(element->ObjectEnum()){
-
-				case TriaEnum: {
-					IssmDouble values[3];
-					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Pid()];
-					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
-					return;
-				}
-				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
-			}
-		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
-	}
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-
-	/*Intermediaries*/
-	Element *element      = NULL;
-	Parameters* parameters= NULL;
-	int         dim;
-
-	/*Recover element*/
-	element=(Element*)helement->delivers();
-
-	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
-
-	switch(type){
-
-		case VertexEnum:
-
-			switch(element->ObjectEnum()){
-
-				case TriaEnum: {
-										IssmDouble values[3];
-										for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Sid()]; //use sid list, to index into serial oriented vector 
-										this->inputs->AddInput(new TriaInput(name,values,P1Enum));
-										/*Special case for rheology B in 2D: Pourave land for this solution{{{*/
-										if(name==MaterialsRheologyBEnum){
-											/*Are we in 2D?:*/
-											if(element->ObjectEnum()==TriaEnum){
-												parameters=((Tria*)(element))->parameters;
-											}
-											else{
-												parameters=((Penta*)(element))->parameters;
-											}
-											parameters->FindParam(&dim,MeshDimensionEnum);
-											if(dim==2){
-												/*Dupliacte rheology input: */
-												this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
-											}
-										}
-										/*}}}*/
-										return;
-									}
-				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
-			}
-		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
-	}
-
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromMatrixDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void  Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromConstant(int constant, int name) {{{*/
-void  Matdamageice::InputUpdateFromConstant(int constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromConstant(bool constant, int name) {{{*/
-void  Matdamageice::InputUpdateFromConstant(bool constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromSolution{{{*/
-void  Matdamageice::InputUpdateFromSolution(IssmDouble* solution){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromIoModel{{{*/
-void Matdamageice::InputUpdateFromIoModel(int index, IoModel* iomodel){
-
-	int i,j;
-	bool   control_analysis;
-	int    num_control_type;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
-	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
-
-	if(iomodel->dim==2){
-
-		/*Intermediaries*/
-		const int num_vertices = 3; //Tria has 3 vertices
-		IssmDouble    nodeinputs[num_vertices];
-		IssmDouble    cmmininputs[num_vertices];
-		IssmDouble    cmmaxinputs[num_vertices];
-
-		/*Get B*/
-		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
-			this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,nodeinputs,P1Enum));
-		}
-
-		/*Get n*/
-		if (iomodel->Data(MaterialsRheologyNEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
-			this->inputs->AddInput(new TriaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
-		}
-
-		/*Get Z*/
-		if (iomodel->Data(MaterialsRheologyZEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+i]-1];
-			this->inputs->AddInput(new TriaInput(MaterialsRheologyZbarEnum,nodeinputs,P1Enum));
-		}
-
-		/*Control Inputs*/
-		#ifdef _HAVE_CONTROL_
-		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
-			for(i=0;i<num_control_type;i++){
-				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
-					case MaterialsRheologyBbarEnum:
-						if (iomodel->Data(MaterialsRheologyBEnum)){
-							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
-						}
-						break;
-					case MaterialsRheologyZbarEnum:
-						if (iomodel->Data(MaterialsRheologyZEnum)){
-							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+j]-1];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyZbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
-						}
-						break;
-
-				}
-			}
-		}
-		#endif
-	}
-
-	/*if 3d*/
-	#ifdef _HAVE_3D_
-	else if(iomodel->dim==3){
-
-		/*Intermediaries*/
-		const int num_vertices = 6; //Penta has 6 vertices
-		IssmDouble    nodeinputs[num_vertices];
-		IssmDouble    cmmininputs[num_vertices];
-		IssmDouble    cmmaxinputs[num_vertices];
-
-		/*Get B*/
-		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
-			this->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,nodeinputs,P1Enum));
-		}
-
-		/*Get n*/
-		if (iomodel->Data(MaterialsRheologyNEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
-			this->inputs->AddInput(new PentaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
-		}
-
-		/*Get Z*/
-		if (iomodel->Data(MaterialsRheologyZEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+i]-1];
-			this->inputs->AddInput(new PentaInput(MaterialsRheologyZEnum,nodeinputs,P1Enum));
-		}
-
-		/*Control Inputs*/
-		#ifdef _HAVE_CONTROL_
-		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
-			for(i=0;i<num_control_type;i++){
-				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
-					case MaterialsRheologyBbarEnum:
-						if (iomodel->Data(MaterialsRheologyBEnum)){
-							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
-						}
-						break;
-					case MaterialsRheologyZbarEnum:
-						if (iomodel->Data(MaterialsRheologyZEnum)){
-							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+j]-1];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyZEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
-						}
-						break;
-				}
-			}
-		}
-		#endif
-	}
-	#endif
-	else{
-		_error_("Mesh type not supported yet!");
-	}
-
-	return;
-}
-/*}}}*/
-/*FUNCTION Matdamageice::IsInput{{{*/
-bool Matdamageice::IsInput(int name){
-	if (
-				name==MaterialsRheologyBEnum ||
-				name==MaterialsRheologyBbarEnum ||
-				name==MaterialsRheologyNEnum ||
-				name==MaterialsRheologyZEnum ||
-				name==MaterialsRheologyZbarEnum
-		){
-		return true;
-	}
-	else return false;
-}
-/*}}}*/
Index: sm/trunk/src/c/classes/Materials/Matdamageice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matdamageice.h	(revision 16559)
+++ 	(revision )
@@ -1,66 +1,0 @@
-/*!\file Matdamageice.h
- * \brief: header file for matice object
- */
-
-#ifndef MATDAMAGEICE_H_
-#define MATDAMAGEICE_H_
-
-/*Headers:*/
-/*{{{*/
-#include "./Material.h"
-class IoModel;
-/*}}}*/
-
-class Matdamageice: public Material{
-
-	private: 
-		int	   mid;
-		Hook* helement;
-
-	public:
-		/*Matdamageice constructors, destructors: {{{*/
-		Matdamageice();
-		Matdamageice(int mid,int i, IoModel* iomodel);
-		~Matdamageice();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
-		Object* copy();
-		/*}}}*/
-		/*Update virtual functions definitions: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols, int name, int type);
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromConstant(IssmDouble constant, int name);
-		void  InputUpdateFromConstant(int constant, int name);
-		void  InputUpdateFromConstant(bool constant, int name);
-		void  InputUpdateFromSolution(IssmDouble* solution);
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
-		/*}}}*/
-		/*Material virtual functions resolution: {{{*/
-		void   InputDuplicate(int original_enum,int new_enum);
-		void   Configure(Elements* elements);
-		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum);
-		void   SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin);
-		void   GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
-		void   GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
-		void   GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon);
-		void   GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
-		void   GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
-		void   GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		void   GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		void   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		IssmDouble GetA();
-		IssmDouble GetB();
-		IssmDouble GetBbar();
-		IssmDouble GetN();
-		IssmDouble GetZ();
-		IssmDouble GetZbar();
-		bool   IsInput(int name);
-		/*}}}*/
-};
-
-#endif  /* _MATICE_H_ */
Index: /issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Material.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Materials/Material.h	(revision 16560)
@@ -27,8 +27,9 @@
 		virtual void       GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum)=0;
 		virtual void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity2dvertical(IssmDouble* pviscosity, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon)=0;
 		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
-		virtual void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
@@ -38,6 +39,6 @@
 		virtual IssmDouble GetBbar()=0;
 		virtual IssmDouble GetN()=0;
-		virtual IssmDouble GetZ()=0;
-		virtual IssmDouble GetZbar()=0;
+		virtual IssmDouble GetD()=0;
+		virtual IssmDouble GetDbar()=0;
 
 };
Index: /issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 16560)
@@ -175,4 +175,23 @@
 }
 /*}}}*/
+/*FUNCTION Matice::GetD {{{*/
+IssmDouble Matice::GetD(){
+
+	/*Output*/
+	IssmDouble D;
+
+	inputs->GetInputAverage(&D,DamageDEnum);
+	return D;
+}
+/*}}}*/
+/*FUNCTION Matice::GetDbar {{{*/
+IssmDouble Matice::GetDbar(){
+
+	/*Output*/
+	IssmDouble Dbar;
+	inputs->GetInputAverage(&Dbar,DamageDbarEnum);
+	return Dbar;
+}
+/*}}}*/
 /*FUNCTION Matice::GetVectorFromInputs{{{*/
 void  Matice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
@@ -210,5 +229,5 @@
 void  Matice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
 	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
-												    B
+												    (1-D) B
 	  viscosity= -------------------------------------------------------------------
 						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
@@ -229,13 +248,14 @@
 	/*Intermediary: */
 	IssmDouble A,e;
-	IssmDouble B,n;
+	IssmDouble B,D,n;
 
 	/*Get B and n*/
 	B=GetBbar();
 	n=GetN();
+	D=GetDbar();
 
 	if (n==1){
 		/*Viscous behaviour! viscosity=B: */
-		viscosity=B/2;
+		viscosity=(1-D)*B/2;
 	}
 	else{
@@ -257,5 +277,5 @@
 			else{
 				e=(n-1)/(2*n);
-				viscosity=B/(2*pow(A,e));
+				viscosity=(1-D)*B/(2*pow(A,e));
 			}
 		}
@@ -266,4 +286,5 @@
 	_assert_(B>0);
 	_assert_(n>0);
+	_assert_(D>=0 && D<1);
 
 	/*Return: */
@@ -271,4 +292,70 @@
 }
 /*}}}*/
+/*FUNCTION Matice::GetViscosity2dvertical {{{*/
+void  Matice::GetViscosity2dvertical(IssmDouble* pviscosity, IssmDouble* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+									   (1-D) B
+	  viscosity= --------------------------------------
+						  2[ exx^2+eyy^2+ 2exy^2]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary: */
+	IssmDouble A,e;
+	IssmDouble B,D,n;
+
+	/*Get B and n*/
+	B=GetB();
+	n=GetN();
+	D=GetD();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=(1-D)*B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow(10.,14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=epsilon[0];
+			eyy=epsilon[1];
+			exy=epsilon[2];
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=exx*exx+eyy*eyy+2.*exy*exy;
+			if(A==0.){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*2.e+17;
+			}
+			else{
+				e=(n-1.)/(2.*n);
+				viscosity=(1.-D)*B/(2.*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(D>=0 && D<1);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
 /*FUNCTION Matice::GetViscosity3d {{{*/
 void  Matice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
@@ -276,5 +363,5 @@
 	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
-	 *                                               B
+	 *                                               (1-D)*B
 	 * viscosity3d= -------------------------------------------------------------------
 	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
@@ -295,13 +382,14 @@
 	/*Intermediaries: */
 	IssmDouble A,e;
-	IssmDouble B,n;
+	IssmDouble B,D,n;
 
 	/*Get B and n*/
 	B=GetB();
+	D=GetD();
 	n=GetN();
 
 	if (n==1){
 		/*Viscous behaviour! viscosity3d=B: */
-		viscosity3d=B/2;
+		viscosity3d=(1-D)*B/2;
 	}
 	else{
@@ -328,5 +416,5 @@
 				e=(n-1)/2/n;
 
-				viscosity3d=B/(2*pow(A,e));
+				viscosity3d=(1-D)*B/(2*pow(A,e));
 			}
 		}
@@ -337,4 +425,5 @@
 	_assert_(B>0);
 	_assert_(n>0);
+	_assert_(D>=0 && D<1);
 
 	/*Assign output pointers:*/
@@ -346,5 +435,5 @@
 	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
-	 *                                          B
+	 *                                          (1-D)*B
 	 * viscosity3d= -------------------------------------------------------------------
 	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
@@ -365,5 +454,5 @@
 	/*Intermediaries: */
 	IssmDouble A,e;
-	IssmDouble B,n;
+	IssmDouble B,D,n;
 	IssmDouble eps0;
 
@@ -371,9 +460,10 @@
 	eps0=pow(10.,-27);
 	B=GetB();
+	D=GetD();
 	n=GetN();
 
 	if (n==1){
 		/*Viscous behaviour! viscosity3d=B: */
-		viscosity3d=B/2;
+		viscosity3d=(1-D)*B/2;
 	}
 	else{
@@ -400,5 +490,5 @@
 			else{
 				e=(n-1)/2/n;
-				viscosity3d=B/(2*pow(A,e));
+				viscosity3d=(1-D)*B/(2*pow(A,e));
 			}
 		}
@@ -409,4 +499,5 @@
 	_assert_(B>0);
 	_assert_(n>0);
+	_assert_(D>=0 && D<1);
 
 	/*Assign output pointers:*/
@@ -418,5 +509,5 @@
 	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
-	 *  										                1
+	 *  										                (1-D)
 	 * viscosity= -------------------------------------------------------------------
 	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
@@ -434,8 +525,8 @@
 	/*Intermediary value A and exponent e: */
 	IssmDouble A,e;
-	IssmDouble B,n;
-
-	/*Get B and n*/
-	B=GetBbar();
+	IssmDouble D,n;
+
+	/*Get D and n*/
+	D=GetDbar();
 	n=GetN();
 
@@ -445,18 +536,74 @@
 		exy=*(epsilon+2);
 
+		/*Build viscosity: mu2=(1-D)/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow(10.,17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=(1-D)/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow(10.,17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(D>=0 && D<1);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityDComplement {{{*/
+void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity derivative for control method d(mu)/dD: 
+	 *
+	 *  										               B 
+	 * dviscosity= - -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
 		/*Build viscosity: mu2=B/(2*A^e) */
 		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
 		if(A==0){
 			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow(10.,17);
+			viscosity_complement=- 2.25*pow(10.,17);
 		}
 		else{
 			e=(n-1)/(2*n);
 
-			viscosity_complement=1/(2*pow(A,e));
+			viscosity_complement=- B/(2*pow(A,e));
 		}
 	}
 	else{
-		viscosity_complement=4.5*pow(10.,17);
+		viscosity_complement=- 4.5*pow(10.,17);
 	}
 
@@ -464,5 +611,5 @@
 	_assert_(B>0);
 	_assert_(n>0);
-	_assert_(viscosity_complement>0);
+	_assert_(viscosity_complement<0);
 
 	/*Return: */
@@ -620,7 +767,7 @@
 
 	/*Intermediaries*/
-	Element *element      = NULL;
-	Parameters* parameters= NULL;
-	int         dim;
+	Element    *element    = NULL;
+	Parameters *parameters = NULL;
+	int         meshtype;
 
 	/*Recover element*/
@@ -649,6 +796,6 @@
 							parameters=((Penta*)(element))->parameters;
 						}
-						parameters->FindParam(&dim,MeshDimensionEnum);
-						if(dim==2){
+						parameters->FindParam(&meshtype,MeshTypeEnum);
+						if(meshtype==Mesh2DhorizontalEnum){
 							/*Duplicate rheology input: */
 							this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
@@ -709,11 +856,11 @@
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
 
-	if(iomodel->dim==2){
+	if(iomodel->meshtype==Mesh2DhorizontalEnum){
 
 		/*Intermediaries*/
-		const int num_vertices = 3; //Tria has 3 vertices
-		IssmDouble    nodeinputs[num_vertices];
-		IssmDouble    cmmininputs[num_vertices];
-		IssmDouble    cmmaxinputs[num_vertices];
+		const int  num_vertices = 3; //Tria has 3 vertices
+		IssmDouble nodeinputs[num_vertices];
+		IssmDouble cmmininputs[num_vertices];
+		IssmDouble cmmaxinputs[num_vertices];
 
 		/*Get B*/
@@ -727,4 +874,10 @@
 			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
 			this->inputs->AddInput(new TriaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
+		}
+
+		/*Get D:*/
+		if (iomodel->Data(DamageDEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(DamageDEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new TriaInput(DamageDbarEnum,nodeinputs,P1Enum));
 		}
 
@@ -743,4 +896,13 @@
 						}
 						break;
+					case DamageDbarEnum:
+						if (iomodel->Data(DamageDEnum)){
+							_assert_(iomodel->Data(DamageDEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(DamageDEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(DamageDbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
 				}
 			}
@@ -748,8 +910,32 @@
 		#endif
 	}
-
-	/*if 3d*/
+	else if(iomodel->meshtype==Mesh2DverticalEnum){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 vertices
+		IssmDouble    nodeinputs[num_vertices];
+		IssmDouble    cmmininputs[num_vertices];
+		IssmDouble    cmmaxinputs[num_vertices];
+
+		/*Get B*/
+		if (iomodel->Data(MaterialsRheologyBEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new TriaInput(MaterialsRheologyBEnum,nodeinputs,P1Enum));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new TriaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
+		}
+
+		/*Get D:*/
+		if (iomodel->Data(DamageDEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(DamageDEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new TriaInput(DamageDEnum,nodeinputs,P1Enum));
+		}
+	}
 	#ifdef _HAVE_3D_
-	else if(iomodel->dim==3){
+	else if(iomodel->meshtype==Mesh3DEnum){
 
 		/*Intermediaries*/
@@ -770,5 +956,11 @@
 			this->inputs->AddInput(new PentaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
 		}
-
+		
+		/*Get D*/
+		if (iomodel->Data(DamageDEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(DamageDEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new PentaInput(DamageDEnum,nodeinputs,P1Enum));
+		}
+		
 		/*Control Inputs*/
 		#ifdef _HAVE_CONTROL_
@@ -785,4 +977,14 @@
 						}
 						break;
+					case DamageDbarEnum:
+						if (iomodel->Data(DamageDEnum)){
+							_assert_(iomodel->Data(DamageDEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(DamageDEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(DamageDEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+
 				}
 			}
@@ -804,5 +1006,8 @@
 				name==MaterialsRheologyBbarEnum ||
 				name==MaterialsRheologyNEnum ||
-				name==QmuMaterialsRheologyBEnum
+				name==QmuMaterialsRheologyBEnum ||
+				name==DamageDEnum ||
+				name==DamageDbarEnum
+
 		){
 		return true;
Index: /issm/trunk/src/c/classes/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Materials/Matice.h	(revision 16560)
@@ -54,8 +54,9 @@
 		void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
+		void       GetViscosity2dvertical(IssmDouble* pviscosity, IssmDouble* pepsilon);
 		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
 		void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon);
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
-		void GetViscosityZComplement(IssmDouble*, IssmDouble*){_error_("not supported");};
+		void       GetViscosityDComplement(IssmDouble*, IssmDouble*);
 		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon);
@@ -64,6 +65,6 @@
 		IssmDouble GetB();
 		IssmDouble GetBbar();
-		IssmDouble GetZ(){_error_("not supported");};
-		IssmDouble GetZbar(){_error_("not supported");};
+		IssmDouble GetD();
+		IssmDouble GetDbar();
 		IssmDouble GetN();
 		bool       IsInput(int name);
Index: /issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 16560)
@@ -377,10 +377,36 @@
 /*FUNCTION Matpar::GetEnthalpyDiffusionParameter{{{*/
 IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){
-	if(enthalpy<PureIceEnthalpy(pressure)){
-		return thermalconductivity/(rho_ice*heatcapacity);
-	}
-	else{
-		return 1.045*1.e-4/rho_ice; // K0=1.045*1e-4 from Aschwanden 2012. TODO: fetch K0 from model
-	}
+	/*if (enthalpy<=PureIceEnthalpy(pressure))
+		return thermalconductivity/heatcapacity;
+	else
+		return thermalconductivity/heatcapacity*pow(10.,-5);
+	*/
+
+	IssmDouble eps=0.05*heatcapacity;
+	IssmDouble hpmp=PureIceEnthalpy(pressure);
+	IssmDouble kappa_c=thermalconductivity/heatcapacity;
+	IssmDouble kappa_t=thermalconductivity/heatcapacity*pow(10.,-1);
+	return 1./(1.+exp(-(enthalpy-(hpmp))/eps))*(kappa_t-kappa_c) + kappa_c;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetEnthalpyDiffusionParameterVolume{{{*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(IssmDouble enthalpy0, IssmDouble enthalpy1, IssmDouble pressure0, IssmDouble pressure1){
+	/*returns kappa depending on distribution of enthalpy over edge of element
+		lambda is the barycentric coordinate that solves H0+(H1-H0)*lambda=H_pureice.
+		it represents the fraction of the ice column which is temperate/cold like H0.
+		if lambda<0 or lambda>1, then the whole ice column is cold or temperate, respectively.
+	*/
+	IssmDouble kappa, kappa0, kappa1;
+	if (enthalpy0!=enthalpy1){
+		IssmDouble lambda=(PureIceEnthalpy(pressure0)-enthalpy0)/(enthalpy1-enthalpy0);
+		if ((lambda>=0.) && (lambda<=1.)){
+			kappa0=GetEnthalpyDiffusionParameter(enthalpy0,pressure0);
+			kappa1=GetEnthalpyDiffusionParameter(enthalpy1,pressure1);
+			kappa=lambda*kappa0+(1.-lambda)*kappa1;
+		}
+	}
+	else
+		kappa=GetEnthalpyDiffusionParameter(enthalpy0, pressure0);
+	return kappa;
 }
 /*}}}*/
@@ -393,5 +419,5 @@
 	if(enthalpy<PureIceEnthalpy(pressure)){
 		temperature=referencetemperature+enthalpy/heatcapacity;
-		waterfraction=0;
+		waterfraction=0.;
 	}
 	else{
Index: /issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 16560)
@@ -80,12 +80,13 @@
 		/*}}}*/
 		/*Material virtual functions resolution: {{{*/
-		void   InputDuplicate(int original_enum,int new_enum);
-		void   Configure(Elements* elements);
-		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){return;}
+		void       InputDuplicate(int original_enum,int new_enum);
+		void       Configure(Elements* elements);
+		void       GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){return;}
 		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosity2dvertical(IssmDouble* pviscosity, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon){_error_("not supported");};
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
-		void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
@@ -95,6 +96,6 @@
 		IssmDouble GetBbar(){_error_("not supported");};
 		IssmDouble GetN(){_error_("not supported");};
-		IssmDouble GetZ(){_error_("not supported");};
-		IssmDouble GetZbar(){_error_("not supported");};
+		IssmDouble GetD(){_error_("not supported");};
+		IssmDouble GetDbar(){_error_("not supported");};
 		/*}}}*/
 		/*Numerics: {{{*/
@@ -125,4 +126,5 @@
 		IssmDouble PureIceEnthalpy(IssmDouble pressure);
 		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble GetEnthalpyDiffusionParameterVolume(IssmDouble enthalpy0, IssmDouble enthalpy1, IssmDouble pressure0, IssmDouble pressure1);
 		IssmDouble GetLithosphereShearModulus();
 		IssmDouble GetLithosphereDensity();
Index: /issm/trunk/src/c/classes/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/Node.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Node.cpp	(revision 16560)
@@ -13,4 +13,5 @@
 #include "shared/shared.h"
 #include "modules/ModelProcessorx/ModelProcessorx.h"
+#include "../analyses/analyses.h"
 /*}}}*/
 
@@ -21,10 +22,10 @@
 }
 /*}}}*/
-/*FUNCTION Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int approximation) {{{*/
-Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int in_approximation){
+/*FUNCTION Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int approximation) {{{*/
+Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int in_approximation){
 
 	/*Intermediary*/
 	int k,l;
-	int gsize;
+	int *doftypes = NULL;
 
 	/*id: */
@@ -32,5 +33,5 @@
 	this->sid           = node_sid;
 	this->lid           = node_lid;
-	this->analysis_type = analysis_type;
+	this->analysis_enum = analysis_enum;
 
 	/*Initialize coord_system: Identity matrix by default*/
@@ -40,8 +41,12 @@
 	/*indexing:*/
 	this->indexingupdate = true;
-	DistributeNumDofs(&this->indexing,analysis_type,in_approximation); //number of dofs per node
-	gsize=this->indexing.gsize;
-
-	if(analysis_type==StressbalanceAnalysisEnum)
+
+	Analysis* analysis = EnumToAnalysis(analysis_enum);
+	int numdofs        = analysis->DofsPerNode(&doftypes,iomodel->meshtype,in_approximation);
+	indexing.Init(numdofs,doftypes);
+	xDelete<int>(doftypes);
+	delete analysis;
+
+	if(analysis_enum==StressbalanceAnalysisEnum)
 	 this->approximation=in_approximation;
 	else
@@ -50,5 +55,5 @@
 	/*Stressbalance Horiz*/
 	#ifdef _HAVE_STRESSBALANCE_
-	if(analysis_type==StressbalanceAnalysisEnum){
+	if(analysis_enum==StressbalanceAnalysisEnum){
 
 		/*Coordinate system provided, convert to coord_system matrix*/
@@ -57,5 +62,5 @@
 		_assert_(sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]) >1.e-4);
 
-		if(iomodel->dim==3){
+		if(iomodel->meshtype==Mesh3DEnum){
 			/*We have a  3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
 			_assert_(iomodel->Data(MeshVertexonbedEnum)); 
@@ -87,14 +92,14 @@
 	/*2d solutions in 3d, we need to constrain all the nodes that are not on base*/
 	if(
-				analysis_type==FreeSurfaceBaseAnalysisEnum || 
-				analysis_type==MasstransportAnalysisEnum || 
-				analysis_type==MeltingAnalysisEnum || 
-				analysis_type==BedSlopeAnalysisEnum || 
-				analysis_type==SurfaceSlopeAnalysisEnum || 
-				analysis_type==BalancethicknessAnalysisEnum ||
-				analysis_type==HydrologyDCInefficientAnalysisEnum ||
-				analysis_type==HydrologyDCEfficientAnalysisEnum
+				analysis_enum==FreeSurfaceBaseAnalysisEnum || 
+				analysis_enum==MasstransportAnalysisEnum || 
+				analysis_enum==MeltingAnalysisEnum || 
+				analysis_enum==L2ProjectionBaseAnalysisEnum || 
+				analysis_enum==BalancethicknessAnalysisEnum ||
+				analysis_enum==HydrologyDCInefficientAnalysisEnum ||
+				analysis_enum==DamageEvolutionAnalysisEnum || 
+				analysis_enum==HydrologyDCEfficientAnalysisEnum
 				){
-		if(iomodel->dim==3){
+		if(iomodel->meshtype==Mesh3DEnum || iomodel->meshtype==Mesh2DverticalEnum){
 			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
 			_assert_(iomodel->Data(MeshVertexonbedEnum));
@@ -104,6 +109,9 @@
 		}
 	}
-	if(analysis_type==FreeSurfaceTopAnalysisEnum){
-		if(iomodel->dim==3){
+	if(
+				analysis_enum==FreeSurfaceTopAnalysisEnum ||
+				analysis_enum==L2ProjectionTopAnalysisEnum
+				){
+		if(iomodel->meshtype==Mesh3DEnum || iomodel->meshtype==Mesh2DverticalEnum){
 			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
 			_assert_(iomodel->Data(MeshVertexonsurfaceEnum));
@@ -129,5 +137,5 @@
 	_printf_("   id : " << id << "\n");
 	_printf_("   sid: " << sid << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   analysis_enum: " << EnumToStringx(analysis_enum) << "\n");
 	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
 	_printf_("   indexingupdate: " << indexingupdate << "\n");
@@ -142,5 +150,5 @@
 	_printf_("   id: " << id << "\n");
 	_printf_("   sid: " << sid << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   analysis_enum: " << EnumToStringx(analysis_enum) << "\n");
 	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
 	_printf_("   indexingupdate: " << indexingupdate << "\n");
@@ -366,6 +374,6 @@
 #endif
 /*FUNCTION Node::InAnalysis{{{*/
-bool Node::InAnalysis(int in_analysis_type){
-	if (in_analysis_type==this->analysis_type) return true;
+bool Node::InAnalysis(int in_analysis_enum){
+	if (in_analysis_enum==this->analysis_enum) return true;
 	else return false;
 }
@@ -402,27 +410,4 @@
 	DofInFSet(dof-1);
 	this->indexing.svalues[dof-1]=0.;
-}
-/*}}}*/
-/*FUNCTION Node::CreateVecSets {{{*/
-void  Node::CreateVecSets(Vector<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s){
-
-	IssmDouble gvalue=1.; //all nodes are in the g set;
-	IssmDouble value;
-
-	for(int i=0;i<this->indexing.gsize;i++){
-
-		/*g set: */
-		pv_g->SetValue(indexing.gdoflist[i],gvalue,INS_VAL);
-
-		/*f set: */
-		value=(IssmDouble)this->indexing.f_set[i];
-		pv_f->SetValue(indexing.gdoflist[i],value,INS_VAL);
-
-		/*s set: */
-		value=(IssmDouble)this->indexing.s_set[i];
-		pv_s->SetValue(indexing.gdoflist[i],value,INS_VAL);
-
-	}
-
 }
 /*}}}*/
@@ -575,16 +560,4 @@
 	return indexing.clone;
 
-}
-/*}}}*/
-/*FUNCTION Node::UpdateSpcs {{{*/
-void   Node::UpdateSpcs(IssmDouble* ys){
-
-	int count = 0;
-	for(int i=0;i<this->indexing.gsize;i++){
-		if(this->indexing.s_set[i]){
-			this->indexing.svalues[i]=ys[this->indexing.sdoflist[count]];
-			count++;
-		}
-	}
 }
 /*}}}*/
@@ -1128,9 +1101,8 @@
 void CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array){/*{{{*/
 
-	int     i,counter;
-	int     numdofs           = 0;
+	int         i,counter;
+	int         numdofs   = 0;
 	IssmDouble  norm;
-	IssmDouble *transform         = NULL;
-	IssmDouble *values            = NULL;
+	IssmDouble *transform = NULL;
 	IssmDouble  coord_system[3][3];
 
Index: /issm/trunk/src/c/classes/Node.h
===================================================================
--- /issm/trunk/src/c/classes/Node.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Node.h	(revision 16560)
@@ -36,10 +36,10 @@
 		bool         indexingupdate;
 		DofIndexing  indexing;
-		int          analysis_type;
+		int          analysis_enum;
 		IssmDouble   coord_system[3][3];
 
 		/*Node constructors, destructors*/
 		Node();
-		Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int approximation_in);
+		Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int approximation_in);
 		~Node();
 
@@ -59,5 +59,5 @@
 		void  GetCoordinateSystem(IssmDouble* coord_system_out);
 #endif
-		bool  InAnalysis(int analysis_type);
+		bool  InAnalysis(int analysis_enum);
 		int   GetApproximation();
 		int   GetNumberOfDofs(int approximation_enum,int setenum);
@@ -68,5 +68,4 @@
 		void  DofInFSet(int dof);
 		int   GetDof(int dofindex,int setenum);
-		void  CreateVecSets(Vector<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s);
 		void  GetDofList(int* poutdoflist,int approximation_enum,int setenum);
 		void  GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
@@ -75,5 +74,4 @@
 		void  Activate(void);
 		void  Deactivate(void);
-		void  UpdateSpcs(IssmDouble* ys);
 		void  ReindexingDone(void);
 		bool  RequiresDofReindexing(void);
Index: /issm/trunk/src/c/classes/Params/BoolParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 16560)
@@ -65,9 +65,2 @@
 }
 /*}}}*/
-
-/*BoolParam virtual functions definitions: */
-/*FUNCTION BoolParam::GetParameterName{{{*/
-void BoolParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Params/BoolParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/BoolParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/BoolParam.h	(revision 16560)
@@ -68,6 +68,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/DataSetParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 16560)
@@ -68,9 +68,4 @@
 
 /*DataSetParam virtual functions definitions: */
-/*FUNCTION DataSetParam::GetParameterName{{{*/
-void DataSetParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION DataSetParam::GetParameterValue{{{*/
 void DataSetParam::GetParameterValue(DataSet** pdataset){
Index: /issm/trunk/src/c/classes/Params/DataSetParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(DataSet* dataset){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a DataSet yet");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 16560)
@@ -183,9 +183,4 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::GetParameterName{{{*/
-void DoubleMatArrayParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION DoubleMatArrayParam::SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){{{*/
 void  DoubleMatArrayParam::SetValue(IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
Index: /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h	(revision 16560)
@@ -71,7 +71,4 @@
 		void  SetValue(FILE* fid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array);
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 16560)
@@ -58,5 +58,5 @@
 	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
 	for(i=0;i<this->M;i++){
-		for(i=0;i<this->N;i++){
+		for(j=0;j<this->N;j++){
 			_printf_(i << " " << j << " " << *(this->value+N*i+j) << "\n");
 		}
@@ -101,9 +101,4 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::GetParameterName{{{*/
-void DoubleMatParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION DoubleMatParam::SetValue{{{*/
 void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){
Index: /issm/trunk/src/c/classes/Params/DoubleMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleMatParam.h	(revision 16560)
@@ -70,7 +70,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/DoubleParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 16560)
@@ -64,9 +64,4 @@
 
 /*DoubleParam virtual functions definitions: */
-/*FUNCTION DoubleParam::GetParameterName{{{*/
-void DoubleParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(int* pinteger){{{*/
 void DoubleParam::GetParameterValue(int* pinteger){
Index: /issm/trunk/src/c/classes/Params/DoubleParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 16560)
@@ -116,9 +116,4 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::GetParameterName{{{*/
-void DoubleVecParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION DoubleVecParam::SetValue{{{*/
 void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){
Index: /issm/trunk/src/c/classes/Params/DoubleVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleVecParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/DoubleVecParam.h	(revision 16560)
@@ -69,6 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/FileParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 16560)
@@ -65,9 +65,2 @@
 }
 /*}}}*/
-
-/*FileParam virtual functions definitions: */
-/*FUNCTION FileParam::GetParameterName{{{*/
-void FileParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Params/FileParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/FileParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/FileParam.h	(revision 16560)
@@ -68,7 +68,4 @@
 		void  SetValue(FILE* fid){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/GenericParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/GenericParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/GenericParam.h	(revision 16560)
@@ -55,6 +55,4 @@
                 /*Param vritual function definitions: {{{*/
                 int   InstanceEnum(){return myEnumVal;}
-                void GetParameterName(char**pname) {EnumToStringx(pname,this->myEnumVal);}
-
                 P& GetParameterValue() { return myP;}
                 const P& GetParameterValue()const { return myP;};
Index: /issm/trunk/src/c/classes/Params/IntMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 16560)
@@ -58,5 +58,5 @@
 	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
 	for(i=0;i<this->M;i++){
-		for(i=0;i<this->N;i++){
+		for(j=0;j<this->N;j++){
 			_printf_("(" << i << "," << j << ") " << *(this->value+N*i+j) << "\n");
 		}
@@ -96,9 +96,4 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::GetParameterName{{{*/
-void IntMatParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION IntMatParam::SetValue{{{*/
 void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){
Index: /issm/trunk/src/c/classes/Params/IntMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntMatParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntMatParam.h	(revision 16560)
@@ -70,7 +70,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/IntParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 16560)
@@ -65,9 +65,2 @@
 }
 /*}}}*/
-
-/*IntParam virtual functions definitions: */
-/*FUNCTION IntParam::GetParameterName{{{*/
-void IntParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Params/IntParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 16560)
@@ -110,9 +110,4 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::GetParameterName{{{*/
-void IntVecParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION IntVecParam::SetValue{{{*/
 void  IntVecParam::SetValue(int* intarray,int in_M){
Index: /issm/trunk/src/c/classes/Params/IntVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntVecParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/IntVecParam.h	(revision 16560)
@@ -70,6 +70,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/MatrixParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 16560)
@@ -84,9 +84,4 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::GetParameterName{{{*/
-void MatrixParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION MatrixParam::SetValue{{{*/
 void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
Index: /issm/trunk/src/c/classes/Params/MatrixParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/MatrixParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/MatrixParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/Param.h
===================================================================
--- /issm/trunk/src/c/classes/Params/Param.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/Param.h	(revision 16560)
@@ -55,5 +55,4 @@
 		virtual void  SetValue(FILE* fid)=0;
 		virtual void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array)=0;
-		virtual void  GetParameterName(char**pname)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 16560)
@@ -524,5 +524,5 @@
 	}
 	if(found==-1){
-		/*still haven't found a list of petsc options, go find the default one, for analysis type NoneAnalysisEnum: */
+		/*still haven't found a list of petsc options, go find the default one, for analysis type DefaultAnalysisEnum: */
 		for(i=0;i<numanalyses;i++){
 			if(analyses[i]==DefaultAnalysisEnum){
Index: /issm/trunk/src/c/classes/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 16560)
@@ -128,9 +128,4 @@
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::GetParameterName{{{*/
-void StringArrayParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION StringArrayParam::SetValue{{{*/
 void  StringArrayParam::SetValue(char** stringarray,int M){
Index: /issm/trunk/src/c/classes/Params/StringArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/StringArrayParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/StringArrayParam.h	(revision 16560)
@@ -70,6 +70,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/StringParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 16560)
@@ -83,9 +83,4 @@
 }
 /*}}}*/
-/*FUNCTION StringParam::GetParameterName{{{*/
-void StringParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION StringParam::SetValue{{{*/
 void  StringParam::SetValue(char* string){
Index: /issm/trunk/src/c/classes/Params/StringParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/StringParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/StringParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/TransientParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 16560)
@@ -127,7 +127,2 @@
 }
 /*}}}*/
-/*FUNCTION TransientParam::GetParameterName{{{*/
-void TransientParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Params/TransientParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/TransientParam.h	(revision 16560)
@@ -70,7 +70,4 @@
 		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Params/VectorParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 16560)
@@ -87,9 +87,4 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::GetParameterName{{{*/
-void VectorParam::GetParameterName(char**pname){
-	EnumToStringx(pname,this->enum_type);
-}
-/*}}}*/
 /*FUNCTION VectorParam::SetValue{{{*/
 void  VectorParam::SetValue(Vector<IssmDouble>* vector){
Index: /issm/trunk/src/c/classes/Params/VectorParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/VectorParam.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Params/VectorParam.h	(revision 16560)
@@ -69,7 +69,4 @@
 		void  SetValue(FILE* fid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
-
-		void GetParameterName(char**pname);
-
 		/*}}}*/
 };
Index: sm/trunk/src/c/classes/Patch.cpp
===================================================================
--- /issm/trunk/src/c/classes/Patch.cpp	(revision 16559)
+++ 	(revision )
@@ -1,160 +1,0 @@
-/*!\file Patch.c
- * \brief: implementation of the Patch object
- */
-
-/*Include files */
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
-#include "./classes.h"
-#include "../shared/shared.h"
-
-/*Object constructors and destructors:*/
-/*FUNCTION Patch::Patch() default constructor {{{*/
-Patch::Patch(){
-	this->numrows     = 0;
-	this->numcols     = 0;
-	this->maxvertices = 0;
-	this->maxnodes    = 0;
-	this->values      = NULL;
-}
-/*}}}*/
-/*FUNCTION Patch::Patch(int numrows, int maxvertices, int maxnodes){{{*/
-Patch::Patch(int in_numrows, int in_maxvertices, int in_maxnodes){
-
-	this->numrows=in_numrows;
-	this->maxvertices=in_maxvertices;
-	this->maxnodes=in_maxnodes;
-	this->numcols=1  //enum_type
-		+1           //step
-		+1           //time 
-		+1           //element id
-		+1           //interpolation type
-		+maxvertices //vertices
-		+maxnodes;   //nodes
-
-	//Allocate values and fill with NaN:
-	if (this->numcols*this->numrows==0){
-		this->values=NULL;
-	}
-	else{
-		this->values=xNew<IssmDouble>(this->numcols*this->numrows);
-		for(int i=0;i<this->numrows;i++){
-			for(int j=0;j<this->numcols;j++){
-				this->values[i*this->numcols+j]=NAN;
-			}
-		}
-	}
-
-}
-/*}}}*/
-/*FUNCTION Patch::~Patch(){{{*/
-Patch::~Patch(){
-	xDelete<IssmDouble>(values);
-}
-/*}}}*/
-
-/*Object methods*/
-/*FUNCTION Patch::fillelementinfo{{{*/
-void Patch::fillelementinfo(int count, int element_id, int* vertices_ids, int num_vertices){
-
-	int i;
-	IssmDouble* row=NULL;
-
-	/*point to the start of the row: */
-	row=this->values+count*this->numcols;
-
-	/*Let's remember what is on a row: 
-	 enum_type step time element_id interpolation vertices_ids nodal_values
-	 */
-	row[3]=element_id;
-	for(i=0;i<num_vertices;i++){
-		row[5+i]=vertices_ids[i];
-	}
-
-}
-/*}}}*/
-/*FUNCTION Patch::fillresultinfo{{{*/
-void Patch::fillresultinfo(int count,int enum_type,int step, IssmDouble time, int interpolation, IssmDouble* nodal_values, int num_nodes){
-
-	int i;
-	IssmDouble* row=NULL;
-
-	/*point to the start of the row: */
-	row=this->values+count*this->numcols;
-
-	/*Let's remember what is on a row: 
-	 enum_type step time element_id interpolation vertices_ids nodal_values */
-	row[0]=enum_type;
-	row[1]=(IssmDouble)step;
-	row[2]=time;
-	row[4]=interpolation;
-	for(i=0;i<num_nodes;i++){
-		row[5+this->maxvertices+i]=nodal_values[i];
-	}
-
-}
-/*}}}*/
-/*FUNCTION Patch::Gather{{{*/
-void Patch::Gather(void){
-
-	int         count;
-	int         my_rank;
-	int         num_procs;
-	int         total_numrows;
-	int         node_numrows;
-	IssmDouble     *total_values  = NULL;
-	ISSM_MPI_Status  status;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-	num_procs=IssmComm::GetSize();
-
-	/*First, figure out total number of rows combining all the cpus: */
-	ISSM_MPI_Reduce(&this->numrows,&total_numrows,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&total_numrows,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*return if patch empty*/
-	if(total_numrows==0) return;
-
-	/*Now, allocate buffer to holds all the values, on node 0: */
-	if(my_rank==0)total_values=xNew<IssmDouble>(this->numcols*total_numrows);
-
-	/*Start by copying node 0 values onto total_values: */
-	if(my_rank==0){
-		count=0;
-		xMemCpy<IssmDouble>(total_values+count,this->values,this->numcols*this->numrows);
-		count+=this->numrows*this->numcols;
-	}
-
-	/*Now, ask other nodes to send their values: */
-	for(int i=1;i<num_procs;i++){
-		if (my_rank==i){ 
-			ISSM_MPI_Send(&this->numrows,1,ISSM_MPI_INT,0,1,IssmComm::GetComm());   
-			if (this->numrows)ISSM_MPI_Send(this->values,this->numrows*this->numcols,ISSM_MPI_DOUBLE,0,1,IssmComm::GetComm()); 
-		}
-		if (my_rank==0){
-			ISSM_MPI_Recv(&node_numrows,1,ISSM_MPI_INT,i,1,IssmComm::GetComm(),&status); 
-			if (node_numrows)ISSM_MPI_Recv(total_values+count,node_numrows*this->numcols,ISSM_MPI_DOUBLE,i,1,IssmComm::GetComm(),&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;
-		xDelete<IssmDouble>(this->values);
-		this->values=total_values;
-	}
-	else{
-		this->numrows=0;
-		xDelete<IssmDouble>(this->values);
-	}
-}/*}}}*/
Index: sm/trunk/src/c/classes/Patch.h
===================================================================
--- /issm/trunk/src/c/classes/Patch.h	(revision 16559)
+++ 	(revision )
@@ -1,44 +1,0 @@
-/*!\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;   //largest amount of vertices on a given element, determined by geometry
-		int         maxnodes;      //the largest amout of nodes on a given element, determined by interpolation
-		IssmDouble *values;        //result values
-
-		Patch();
-		Patch(int numrows, int maxvertices, int maxnodes);
-		~Patch();
-		void fillelementinfo(int row, int element_id, int* vertices_ids, int num_vertices);
-		void fillresultinfo(int row,int enum_type,int step, IssmDouble time, int interpolation, IssmDouble* nodal_values, int num_nodes);
-		void Gather(void);
-
-};
-#endif //ifndef _PATCH_H_
Index: /issm/trunk/src/c/classes/Vertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertex.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/Vertex.cpp	(revision 16560)
@@ -21,16 +21,29 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::Vertex(int vertex_id, IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma){{{*/
-Vertex::Vertex(int vertex_id, int vertex_sid,IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma,int vertex_connectivity){
-	this->Init(vertex_id, vertex_sid,vertex_x, vertex_y, vertex_z, vertex_sigma,vertex_connectivity);
-}
-/*}}}*/
 /*FUNCTION Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel) {{{*/
 Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){
 
+	this->id           = vertex_id;
+	this->sid          = vertex_sid;
+	this->pid          = UNDEF;
+
 	_assert_(iomodel->Data(MeshXEnum) && iomodel->Data(MeshYEnum) && iomodel->Data(MeshZEnum));
+	this->x            = iomodel->Data(MeshXEnum)[i];
+	this->y            = iomodel->Data(MeshYEnum)[i];
+	this->z            = iomodel->Data(MeshZEnum)[i];
+	this->meshtype     = iomodel->meshtype;
+
 	_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]);
+	switch(iomodel->meshtype){
+		case Mesh3DEnum:
+		case Mesh2DhorizontalEnum:
+			this->sigma = (iomodel->Data(MeshZEnum)[i]-iomodel->Data(BedEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
+			break;
+		case Mesh2DverticalEnum:
+			this->sigma = (iomodel->Data(MeshYEnum)[i]-iomodel->Data(BedEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
+			break;
+	}
+
+	this->connectivity = iomodel->numbernodetoelementconnectivity[i];
 
 }
@@ -38,20 +51,4 @@
 /*FUNCTION Vertex::~Vertex() {{{*/
 Vertex::~Vertex(){
-	return;
-}
-/*}}}*/
-/*FUNCTION Vertex::Init{{{*/
-void Vertex::Init(int vertex_id, int vertex_sid,IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma,int vertex_connectivity){
-
-	/*all the initialization has been done by the initializer, just fill in the id: */
-	this->id=vertex_id;
-	this->sid=vertex_sid;
-	this->pid=UNDEF;
-	this->x=vertex_x;
-	this->y=vertex_y;
-	this->z=vertex_z;
-	this->sigma=vertex_sigma;
-	this->connectivity=vertex_connectivity;
-
 	return;
 }
@@ -125,8 +122,9 @@
 /*}}}*/
 /*FUNCTION Vertex::UpdatePosition {{{*/
-void  Vertex::UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed){
-
-	IssmDouble oldz,newz;
-	IssmDouble dt,velz;
+void  Vertex::UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* surface,IssmDouble* bed){
+
+	IssmDouble oldy,newy,vely;
+	IssmDouble oldz,newz,velz;
+	IssmDouble dt;
 
 	/*Get time stepping*/
@@ -134,11 +132,18 @@
 
 	/*sigma remains constant. z=bed+sigma*thickness*/
-	oldz = this->z;
-	newz = bed[this->pid]+sigma*thickness[this->pid];
-	velz = (newz-oldz)/dt;
-	this->z = newz;
-
-	/*put vz in vector*/
-	vz->SetValue(this->pid,velz,INS_VAL);
+	if(this->meshtype==Mesh2DverticalEnum){
+		oldy = this->y;
+		newy = bed[this->pid]+sigma*(surface[this->pid] - bed[this->pid]);
+		vely = (newy-oldy)/dt;
+		this->y = newy;
+		vy->SetValue(this->pid,vely,INS_VAL);
+	}
+	else{
+		oldz = this->z;
+		newz = bed[this->pid]+sigma*(surface[this->pid] - bed[this->pid]);
+		velz = (newz-oldz)/dt;
+		this->z = newz;
+		vz->SetValue(this->pid,velz,INS_VAL);
+	}
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Vertex.h
===================================================================
--- /issm/trunk/src/c/classes/Vertex.h	(revision 16559)
+++ /issm/trunk/src/c/classes/Vertex.h	(revision 16560)
@@ -21,4 +21,5 @@
 	public: 
 		bool       clone;
+		int        meshtype;
 		int        id;           // random index
 		int        sid;          // "serial" id (rank of this vertex if the dataset was on 1 cpu)
@@ -32,6 +33,4 @@
 		/*Vertex constructors, destructors {{{*/
 		Vertex();
-		Vertex(int id, int sid,IssmDouble x, IssmDouble y, IssmDouble z, IssmDouble sigma, int connectivity); 
-		void Init(int id, int sid, IssmDouble x, IssmDouble y, IssmDouble z, IssmDouble sigma,int connectivity);
 		Vertex(int id, int sid, int i, IoModel* iomodel);
 		~Vertex();
@@ -51,5 +50,5 @@
 		IssmDouble GetY(void); 
 		IssmDouble GetZ(void); 
-		void       UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
+		void       UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
 		void       DistributePids(int* ppidcount);
 		void       OffsetPids(int pidcount);
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 16559)
+++ /issm/trunk/src/c/classes/classes.h	(revision 16560)
@@ -17,4 +17,5 @@
 #include "./IndependentObject.h"
 #include "./Segment.h"
+#include "./Massfluxatgate.h"
 
 /*Constraints: */
@@ -39,4 +40,6 @@
 #include "./Elements/Penta.h"
 #include "./Elements/PentaRef.h"
+#include "./Elements/Seg.h"
+#include "./Elements/SegRef.h"
 #include "./Elements/Tria.h"
 #include "./Elements/TriaRef.h"
@@ -57,14 +60,8 @@
 #include "./Inputs/PentaInput.h"
 #include "./Inputs/TriaInput.h"
+#include "./Inputs/SegInput.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: */
@@ -77,5 +74,4 @@
 #include "./Materials/Material.h"
 #include "./Materials/Matice.h"
-#include "./Materials/Matdamageice.h"
 #include "./Materials/Matpar.h"
 
@@ -114,5 +110,4 @@
 #include "./DofIndexing.h"
 #include "./IoModel.h"
-#include "./Patch.h"
 #include "./Update.h"
 #include "./FemModel.h"
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 16560)
@@ -495,15 +495,4 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussCenter{{{*/
-void GaussPenta::GaussCenter(void){
-
-	/*update static arrays*/
-	coord1=ONETHIRD;
-	coord2=ONETHIRD;
-	coord3=ONETHIRD;
-	coord4=0.0;
-
-}
-/*}}}*/
 /*FUNCTION GaussPenta::GaussPoint{{{*/
 void GaussPenta::GaussPoint(int ig){
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 16559)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 16560)
@@ -47,5 +47,4 @@
 		void GaussNode(int finitelement,int iv);
 		void GaussFaceTria(int index1, int index2, int index3, int order);
-		void GaussCenter(void);
 		void SynchronizeGaussTria(GaussTria* gauss_tria);
 };
Index: /issm/trunk/src/c/classes/gauss/GaussSeg.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 16560)
+++ /issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 16560)
@@ -0,0 +1,106 @@
+/*!\file GaussSeg.c
+ * \brief: implementation of the GaussSeg object
+ */
+
+#include "./GaussSeg.h"
+#include "../../shared/io/Print/Print.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Numerics/GaussPoints.h"
+#include "../../shared/Numerics/constants.h"
+
+/*GaussSeg constructors and destructors:*/
+/*FUNCTION GaussSeg::GaussSeg(int order) {{{*/
+GaussSeg::GaussSeg(int order){
+
+	IssmPDouble* pcoords1=NULL;
+	IssmPDouble* pweights=NULL;
+
+	/*Get gauss points*/
+	this->numgauss = order;
+	GaussLegendreLinear(&pcoords1,&pweights,order);
+	
+	this->coords1=xNew<IssmDouble>(numgauss);
+	this->weights=xNew<IssmDouble>(numgauss);
+
+	/*cast : */
+	for(int i=0;i<numgauss;i++){
+		this->coords1[i]=pcoords1[i];
+		this->weights[i]=pweights[i];
+	}
+
+	/*Free ressources: */
+	xDelete<IssmPDouble>(pcoords1);
+	xDelete<IssmPDouble>(pweights);
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussSeg::~GaussSeg(){{{*/
+GaussSeg::~GaussSeg(){
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION GaussSeg::Echo{{{*/
+void GaussSeg::Echo(void){
+
+	_printf_("GaussSeg:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
+
+	if (weights){
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
+	if (coords1){
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+
+}
+/*}}}*/
+/*FUNCTION GaussSeg::GaussPoint{{{*/
+void GaussSeg::GaussPoint(int ig){
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+}
+/*}}}*/
+/*FUNCTION GaussSeg::begin{{{*/
+int GaussSeg::begin(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+/*FUNCTION GaussSeg::end{{{*/
+int GaussSeg::end(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/gauss/GaussSeg.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussSeg.h	(revision 16560)
+++ /issm/trunk/src/c/classes/gauss/GaussSeg.h	(revision 16560)
@@ -0,0 +1,34 @@
+/*!\file GaussSeg.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSSEG_H_
+#define _GAUSSSEG_H_
+
+/*Headers:*/
+#include "../../shared/Numerics/types.h"
+
+class GaussSeg{
+
+	private:
+		int numgauss;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+
+	public:
+		IssmDouble weight;
+		IssmDouble coord1;
+
+	public:
+
+		/*GaussSeg constructors, destructors*/
+		GaussSeg(int order);
+		~GaussSeg();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		void GaussPoint(int ig);
+};
+#endif
Index: /issm/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 16560)
@@ -44,5 +44,4 @@
 	IssmPDouble *seg_weights = NULL;
 	IssmDouble  a1,b1,c1,a2,b2,c2;
-	int     i,index3;
 
 	/*Get Segment gauss points*/
@@ -83,5 +82,5 @@
 
 	/*Build Triangle Gauss point*/
-	for(i=0;i<numgauss;i++){
+	for(int i=0;i<numgauss;i++){
 		coords1[i]=0.5*(a1+a2) + 0.5*seg_coords[i]*(a2-a1);
 		coords2[i]=0.5*(b1+b2) + 0.5*seg_coords[i]*(b2-b1);
@@ -107,5 +106,4 @@
 	IssmPDouble *seg_coords  = NULL;
 	IssmPDouble *seg_weights = NULL;
-	int     i,index3;
 
 	/*Get Segment gauss points*/
@@ -120,5 +118,5 @@
 
 	/*Build Triangle Gauss point*/
-	for(i=0;i<numgauss;i++){
+	for(int i=0;i<numgauss;i++){
 		coords1[i]=0.5*(area_coordinates[0][0]+area_coordinates[1][0]) + 0.5*seg_coords[i]*(area_coordinates[1][0]-area_coordinates[0][0]);
 		coords2[i]=0.5*(area_coordinates[0][1]+area_coordinates[1][1]) + 0.5*seg_coords[i]*(area_coordinates[1][1]-area_coordinates[0][1]);
@@ -343,14 +341,4 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussCenter{{{*/
-void GaussTria::GaussCenter(void){
-
-	/*update static arrays*/
-	coord1=ONETHIRD;
-	coord2=ONETHIRD;
-	coord3=ONETHIRD;
-
-}
-/*}}}*/
 /*FUNCTION GaussTria::GaussEdgeCenter{{{*/
 void GaussTria::GaussEdgeCenter(int index1,int index2){
Index: /issm/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 16559)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 16560)
@@ -31,5 +31,5 @@
 		GaussTria(int index1,int index2,int order);
 		GaussTria(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
-		GaussTria(IssmDouble area_coordinates[3][3],int order);
+		GaussTria(IssmDouble area_coordinates[2][3],int order);
 		~GaussTria();
 
@@ -42,5 +42,4 @@
 		void GaussVertex(int iv);
 		void GaussNode(int finitelement,int iv);
-		void GaussCenter(void);
 		void GaussEdgeCenter(int index1,int index2);
 };
Index: /issm/trunk/src/c/classes/gauss/gaussobjects.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/gaussobjects.h	(revision 16559)
+++ /issm/trunk/src/c/classes/gauss/gaussobjects.h	(revision 16560)
@@ -6,4 +6,5 @@
 #define ALL_GAUSS_OBJECTS_H_
 
+#include "./GaussSeg.h"
 #include "./GaussTria.h"
 #include "./GaussPenta.h"
Index: /issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 16560)
@@ -125,5 +125,5 @@
 	/*Output and Intermediaries*/
 	int          nobs,i,index;
-	IssmPDouble  hmin,h2,hmin2,radius2;
+	IssmPDouble  hmin,h2,hmin2;
 	int         *indices      = NULL;
 	Observation *observation  = NULL;
@@ -139,7 +139,4 @@
 		if(hmin<radius) radius=hmin;
 	}
-
-	/*Compute radius square*/
-	radius2 = radius*radius;
 
 	/*Find all observations that are in radius*/
Index: /issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 16560)
@@ -205,5 +205,5 @@
 	QuadtreeBox  *box  = NULL;
 	int           xi,yi;
-	int           level,levelbin;
+	int           levelbin;
 	int           index;
 	double        length,length2;
@@ -212,6 +212,5 @@
 	this->IntergerCoordinates(&xi,&yi,x,y);
 
-	/*Initialize levels*/
-	level    = 0;
+	/*Initialize level*/
 	levelbin = (1L<<this->MaxDepth);// = 2^30
 
@@ -221,7 +220,5 @@
 	/*Find the smallest box where this point is located*/
 	while((box=*pbox) && (box->nbitems<0)){ 
-
-		levelbin>>=1; level+=1; 
-
+		levelbin>>=1;
 		pbox = &box->box[IJ(xi,yi,levelbin)];
 	}
@@ -257,5 +254,5 @@
 	QuadtreeBox  *box  = NULL;
 	int           xi,yi;
-	int           level,levelbin;
+	int           levelbin;
 	int           index = -1;
 	double        length,length2;
@@ -264,6 +261,5 @@
 	this->IntergerCoordinates(&xi,&yi,x,y);
 
-	/*Initialize levels*/
-	level    = 0;
+	/*Initialize level*/
 	levelbin = (1L<<this->MaxDepth);// = 2^30
 
@@ -273,7 +269,5 @@
 	/*Find the smallest box where this point is located*/
 	while((box=*pbox) && (box->nbitems<0)){ 
-
-		levelbin>>=1; level+=1; 
-
+		levelbin>>=1;
 		pbox = &box->box[IJ(xi,yi,levelbin)];
 	}
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 16559)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 16560)
@@ -587,14 +587,2 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::SetDiag{{{*/
-void ElementMatrix::SetDiag(IssmDouble scalar){
-
-	int i;
-
-	if(this->nrows!=this->ncols)_error_("need square matrix in input!");
-
-	for(i=0;i<this->nrows;i++){
-		this->values[this->ncols*i+i]=scalar;
-	}
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 16559)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 16560)
@@ -65,5 +65,4 @@
 		void Transpose(void);
 		void Init(ElementMatrix* Ke);
-		void SetDiag(IssmDouble scalar);
 };
 #endif //#ifndef _ELEMENT_MATRIX_H_
Index: /issm/trunk/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp	(revision 16560)
@@ -0,0 +1,46 @@
+/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype){
+
+	/*output: */
+	void (*adjointcore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			adjointcore=&adjointstressbalance_core;
+			break;
+		case SteadystateSolutionEnum:
+			adjointcore=&adjointstressbalance_core;
+			break;
+		case BalancethicknessSolutionEnum:
+			adjointcore=&adjointbalancethickness_core;
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			adjointcore=&dummy_core;
+			break;
+		default:
+			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(padjointcore);
+	*padjointcore=adjointcore;
+
+}
Index: /issm/trunk/src/c/cores/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/cores/AnalysisConfiguration.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/AnalysisConfiguration.cpp	(revision 16560)
@@ -0,0 +1,141 @@
+/*!\file:  AnalysisConfiguration.cpp
+ * \brief: return type of analyses, number of analyses 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
+
+	/*output: */
+	int  numanalyses;
+	int* analyses=NULL;
+
+	/*Analyses lists*/
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			numanalyses=4;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case SteadystateSolutionEnum:
+			numanalyses=7;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			analyses[4]=EnthalpyAnalysisEnum;
+			analyses[5]=ThermalAnalysisEnum;
+			analyses[6]=MeltingAnalysisEnum;
+			break;
+
+		case ThermalSolutionEnum:
+			numanalyses=3;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=ThermalAnalysisEnum;
+			analyses[1]=MeltingAnalysisEnum;
+			analyses[2]=EnthalpyAnalysisEnum;
+			break;
+
+		case HydrologySolutionEnum:
+			numanalyses=4;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=HydrologyShreveAnalysisEnum;
+			analyses[1]=HydrologyDCInefficientAnalysisEnum;
+			analyses[2]=HydrologyDCEfficientAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case MasstransportSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=MasstransportAnalysisEnum;
+			break;
+
+		case BalancethicknessSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancethicknessSoftSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancevelocitySolutionEnum:
+			numanalyses=3;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancevelocityAnalysisEnum;
+			analyses[1]=SmoothedSurfaceSlopeXAnalysisEnum;
+			analyses[2]=SmoothedSurfaceSlopeYAnalysisEnum;
+			break;
+
+		case SurfaceSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case BedSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case GiaSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=GiaAnalysisEnum;
+			break;
+		
+		case DamageEvolutionSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=DamageEvolutionAnalysisEnum;
+			break;
+
+		case TransientSolutionEnum:
+			numanalyses=12;
+			analyses=xNew<int>(numanalyses);
+			analyses[ 0]=StressbalanceAnalysisEnum;
+			analyses[ 1]=StressbalanceVerticalAnalysisEnum;
+			analyses[ 2]=StressbalanceSIAAnalysisEnum;
+			analyses[ 3]=L2ProjectionBaseAnalysisEnum;
+			analyses[ 4]=ThermalAnalysisEnum;
+			analyses[ 5]=MeltingAnalysisEnum;
+			analyses[ 6]=EnthalpyAnalysisEnum;
+			analyses[ 7]=MasstransportAnalysisEnum;
+			analyses[ 8]=FreeSurfaceBaseAnalysisEnum;
+			analyses[ 9]=FreeSurfaceTopAnalysisEnum;
+			analyses[10]=ExtrudeFromBaseAnalysisEnum;
+			analyses[11]=ExtrudeFromTopAnalysisEnum;
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointers:*/
+	if(pnumanalyses) *pnumanalyses=numanalyses;
+	if(panalyses)    *panalyses=analyses;
+	else              xDelete<int>(analyses);
+}
Index: /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 16560)
@@ -0,0 +1,127 @@
+/*!\file:  CorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			#ifdef _HAVE_STRESSBALANCE_
+			solutioncore=&stressbalance_core;
+			#else
+			_error_("ISSM was not compiled with stressbalance 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 BalancethicknessSolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&balancethickness_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&dummy_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
+		case BalancevelocitySolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&balancevelocity_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 MasstransportSolutionEnum:
+			#ifdef _HAVE_MASSTRANSPORT_
+			solutioncore=&masstransport_core;
+			#else
+			_error_("ISSM was not compiled with masstransport capabilities. Exiting");
+			#endif
+			break;
+
+		case GiaSolutionEnum:
+			#ifdef _HAVE_GIA_
+			solutioncore=&gia_core;
+			#else
+			_error_("ISSM was not compiled with gia capabilities. Exiting");
+			#endif
+			break;
+		case DamageEvolutionSolutionEnum:
+			#ifdef _HAVE_DAMAGE_
+			solutioncore=&damage_core;
+			#else
+			_error_("ISSM was not compiled with damage evolution capabilities. Exiting");
+			#endif
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/trunk/src/c/cores/DakotaSpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/cores/DakotaSpawnCore.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/DakotaSpawnCore.cpp	(revision 16560)
@@ -0,0 +1,187 @@
+/*!\file:  DakotaSpawnCore.cpp
+
+ * \brief: run core ISSM solution using Dakota inputs coming from CPU 0.
+ * \sa qmu.cpp DakotaPlugin.cpp
+ *
+ * This routine needs to be understood simultaneously with qmu.cpp and DakotaPlugin. 
+ * DakotaSpawnCoreParallel is called by all CPUS, with CPU 0 holding Dakota variable values, along 
+ * with variable descriptors. 
+ *
+ * DakotaSpawnCoreParallel takes care of broadcasting the variables and their descriptors across the MPI 
+ * ring. Once this is done, we use the variables to modify the inputs for the solution core. 
+ * For ex, if "rho_ice" is provided, for ex 920, we include "rho_ice" in the inputs, then 
+ * call the core with the modified inputs. This is the way we get Dakota to explore the parameter 
+ * spce of the core. 
+ *
+ * Once the core is called, we process the results of the core, and using the processed results, 
+ * we compute response functions. The responses are computed on all CPUS, but they are targeted 
+ * for CPU 0, which will get these values back to the Dakota engine. 
+ *
+ */ 
+
+/*Includes and prototypes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses);
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses);
+/*}}}*/
+
+/*Notice the d_, which prefixes anything that is being provided to us by the Dakota pluggin. Careful. some things are ours, some are dakotas!: */
+int DakotaSpawnCore(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, void* void_femmodel,int counter){
+
+	char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
+	int        numresponsedescriptors;
+	int        solution_type;
+	bool       control_analysis         = false;
+	void     (*solutioncore)(FemModel*) = NULL;
+	FemModel  *femmodel                 = NULL;
+	bool       nodakotacore             = true;
+
+	/*If counter==-1 on cpu0, it means that the dakota runs are done. In which case, bail out and return 0: */
+	ISSM_MPI_Bcast(&counter,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	if(counter==-1)return 0;
+
+	/*cast void_femmodel to FemModel: */
+	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+
+	if(VerboseQmu()) _printf0_("qmu iteration: " << counter << "\n");
+
+	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
+	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
+
+	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
+	InputUpdateFromDakotax(femmodel,d_variables,d_variables_descriptors,d_numvariables);
+
+	/*Determine solution sequence: */
+	if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
+	WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
+
+	/*Run the core solution sequence: */
+	solutioncore(femmodel);
+
+	/*compute responses: */
+	if(VerboseQmu()) _printf0_("compute dakota responses:\n");
+	femmodel->DakotaResponsesx(d_responses,responses_descriptors,numresponsedescriptors,d_numresponses);
+
+	/*Free ressources:*/
+	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+
+	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
+}
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){ /*{{{*/
+
+	/* * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
+	 * from cpu 0 to all other cpus.
+	 */ 
+
+	int i;
+	int my_rank;
+
+	/*inputs and outputs: */
+	double* variables=NULL;
+	char**  variables_descriptors=NULL;
+	int     numvariables;
+	int     numresponses;
+
+	/*intermediary: */
+	char* string=NULL;
+	int   string_length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*recover inputs from pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	numvariables=*pnumvariables;
+	numresponses=*pnumresponses;
+
+	/*numvariables: */
+	ISSM_MPI_Bcast(&numvariables,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*variables:*/
+	if(my_rank!=0)variables=xNew<double>(numvariables);
+	ISSM_MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
+
+	/*variables_descriptors: */
+	if(my_rank!=0){
+		variables_descriptors=xNew<char*>(numvariables);
+	}
+	for(i=0;i<numvariables;i++){
+		if(my_rank==0){
+			string=variables_descriptors[i];
+			string_length=(strlen(string)+1)*sizeof(char);
+		}
+		ISSM_MPI_Bcast(&string_length,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+		if(my_rank!=0)string=xNew<char>(string_length);
+		ISSM_MPI_Bcast(string,string_length,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+		if(my_rank!=0)variables_descriptors[i]=string;
+	}
+
+	/*numresponses: */
+	ISSM_MPI_Bcast(&numresponses,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pnumvariables=numvariables;
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*pnumresponses=numresponses;
+} /*}}}*/
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses){ /*{{{*/
+
+	/*\brief DakotaFree: free allocations on other cpus, not done by Dakota.*/
+
+	int i;
+	int my_rank;
+
+	double  *variables             = NULL;
+	char   **variables_descriptors = NULL;
+	char   **responses_descriptors = NULL;
+	char    *string                = NULL;
+
+	/*recover pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	responses_descriptors=*presponses_descriptors;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Free variables and variables_descriptors only on cpu !=0*/
+	if(my_rank!=0){
+		xDelete<double>(variables);
+		for(i=0;i<numvariables;i++){
+			string=variables_descriptors[i];
+			xDelete<char>(string);
+		}
+		xDelete<char*>(variables_descriptors);
+	}
+
+	//responses descriptors on every cpu
+	for(i=0;i<numresponses;i++){
+		string=responses_descriptors[i];
+		xDelete<char>(string);
+	}
+	//rest of dynamic allocations.
+	xDelete<char*>(responses_descriptors);
+
+	/*Assign output pointers:*/
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*presponses_descriptors=responses_descriptors;
+} /*}}}*/
Index: /issm/trunk/src/c/cores/DakotaSpawnCore.h
===================================================================
--- /issm/trunk/src/c/cores/DakotaSpawnCore.h	(revision 16560)
+++ /issm/trunk/src/c/cores/DakotaSpawnCore.h	(revision 16560)
@@ -0,0 +1,4 @@
+#ifndef _DAKOTA_SPAWN_CORE_
+#define _DAKOTA_SPAWN_CORE_
+int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
+#endif
Index: /issm/trunk/src/c/cores/ProcessArguments.cpp
===================================================================
--- /issm/trunk/src/c/cores/ProcessArguments.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/ProcessArguments.cpp	(revision 16560)
@@ -0,0 +1,57 @@
+/*!\file:  ProcessArguments.cpp
+ * \brief: process arguments
+ */ 
+
+#include <stdio.h>
+#include <cstring>
+
+#include "../shared/shared.h"
+
+void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ptoolkitsfilename,char** plockfilename,char** prootpath, int argc,char **argv){
+
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *toolkitsfilename  = NULL;
+	char *lockfilename   = NULL;
+	char *rootpath       = NULL;
+	char *rootpatharg    = NULL;
+
+	/*Check input arguments*/
+	if(argc<2)_error_("Usage error: no solution requested");
+	if(argc<3)_error_("Usage error: missing execution directory");
+	if(argc<4)_error_("Usage error: missing model name");
+
+	/*Get requested solution*/
+	*solution_type=StringToEnumx(argv[1]);
+
+	rootpatharg=argv[2];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	}
+
+	modelname=argv[3];
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s%s",rootpath,modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s",modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*ptoolkitsfilename=toolkitsfilename;
+	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+
+}
Index: /issm/trunk/src/c/cores/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/cores/ResetBoundaryConditions.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/ResetBoundaryConditions.cpp	(revision 16560)
@@ -0,0 +1,27 @@
+/*!\file: ResetBoundaryConditions.cpp
+ * \brief: change boundary conditions of a model, using a solution vector from another analysis
+ */ 
+
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/io/io.h"
+
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
+
+	/*variables: */
+	Vector<IssmDouble>* yg = NULL;
+
+	if(VerboseSolution()) _printf0_("   updating boundary conditions...\n");
+
+	/*set current analysis: */
+	femmodel->SetCurrentConfiguration(analysis_type);
+
+	/*retrieve boundary conditions from element inputs :*/
+	GetSolutionFromInputsx(&yg,femmodel);
+
+	/*update spcs using this new vector of constraints: */
+	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
+
+	/*Free ressources:*/
+	delete yg;
+}
Index: /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 16560)
@@ -0,0 +1,57 @@
+/*!\file:  WrapperCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	/*parameters: */
+	bool control_analysis=false;
+	bool tao_analysis=false;
+	bool dakota_analysis=false;
+
+	/* retrieve some parameters that tell us whether wrappers are allowed, or whether we return 
+	 * a pure core. Wrappers can be dakota_core (which samples many solution_cores) or control_core (which 
+	 * carries out adjoint based inversion on a certain core: */
+	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	parameters->FindParam(&tao_analysis,InversionTaoEnum);
+
+	if(nodakotacore)dakota_analysis=false;
+
+	if(dakota_analysis){
+		#ifdef _HAVE_DAKOTA_
+		solutioncore=dakota_core;
+		#else
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		#endif
+	}
+	else if(control_analysis){
+		#ifdef _HAVE_CONTROL_
+		if(tao_analysis) solutioncore=controltao_core;
+		else solutioncore=control_core;
+		#else
+		_error_("ISSM was not compiled with control support, cannot carry out control analysis!");
+		#endif
+	}
+	else CorePointerFromSolutionEnum(&solutioncore,parameters,solutiontype);  /*This means we retrieve a core solution that is not a wrapper*/
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/trunk/src/c/cores/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/ad_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/ad_core.cpp	(revision 16560)
@@ -0,0 +1,356 @@
+/*!\file ad_core
+ * \brief: compute outputs from the AD mode,  using our dependents and independents, and drivers available in Adolc.
+ */
+
+/*Includes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <set>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+/*}}}*/
+
+void ad_core(FemModel* femmodel){
+
+	/*diverse: */
+	int     i;
+	int     dummy;
+	int     num_dependents=0;
+	int     num_independents=0;
+	bool    isautodiff       = false;
+	char   *driver           = NULL;
+	size_t  tape_stats[11];
+
+	/*state variables: */
+	IssmDouble *axp = NULL;
+	double     *xp  = NULL;
+	int my_rank=IssmComm::GetRank();
+
+	/*AD mode on?: */
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+
+		#ifdef _HAVE_ADOLC_
+			if(VerboseAutodiff())_printf0_("   start ad core\n");
+
+			/*First, stop tracing: */
+			trace_off();
+		
+			/*retrieve parameters: */
+			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+	
+			/*if no dependents, no point in running a driver: */
+			if(!(num_dependents*num_independents)) return;
+
+			/*for adolc to run in parallel, we 0 out on rank~=0:*/
+			if (my_rank!=0){
+				num_dependents=0; num_independents=0;
+			}
+			
+			/*Print tape statistics so that user can kill this run if something is off already:*/
+			tapestats(my_rank,tape_stats); //reading of tape statistics
+			if(VerboseAutodiff()){
+				int commSize=IssmComm::GetSize();
+				int *sstats=new int[7];
+				sstats[0]=tape_stats[NUM_OPERATIONS];
+				sstats[1]=tape_stats[OP_FILE_ACCESS];
+				sstats[2]=tape_stats[NUM_LOCATIONS];
+				sstats[3]=tape_stats[LOC_FILE_ACCESS];
+				sstats[4]=tape_stats[NUM_VALUES];
+				sstats[5]=tape_stats[VAL_FILE_ACCESS];
+				sstats[6]=tape_stats[TAY_STACK_SIZE];
+				int *rstats=NULL;
+				if (my_rank==0) rstats=new int[commSize*7];
+				ISSM_MPI_Gather(sstats,7,ISSM_MPI_INT,rstats,7,ISSM_MPI_INT,0,IssmComm::GetComm());
+				if (my_rank==0) {
+					int offset=50;
+					int rOffset=(commSize/10)+1;
+					_printf_("   ADOLC statistics: \n");
+					_printf_("     "<<setw(offset)<<left<<"#independents: " <<setw(12)<<right<<tape_stats[NUM_INDEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"#dependents: " <<setw(12)<<right<<tape_stats[NUM_DEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"max #live active variables: " <<setw(12)<<right<<tape_stats[NUM_MAX_LIVES] << "\n");
+					_printf_("     operations: entry size "<< sizeof(unsigned char) << " Bytes \n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffObufsizeEnum) " <<setw(12)<<right<<tape_stats[OP_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+0] << (rstats[r*7+1]?" ->file":"") << "\n");
+					_printf_("     locations: entry size " << sizeof(locint) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffLbufsizeEnum) " <<setw(12)<<right<<tape_stats[LOC_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+2] << (rstats[r*7+3]?" ->file":"") << "\n");
+					_printf_("     constant values: entry size " << sizeof(double) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffCbufsizeEnum) " <<setw(12)<<right<<tape_stats[VAL_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+4] << (rstats[r*7+5]?" ->file":"") << "\n");
+					_printf_("     Taylor stack: entry size " << sizeof(revreal) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffTbufsizeEnum) " <<setw(12)<<right<<tape_stats[TAY_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+6] << (rstats[r*7+6]>tape_stats[TAY_BUFFER_SIZE]?" ->file":"") << "\n");
+					delete []rstats;
+				}
+				delete [] sstats;
+			}
+
+			/*retrieve state variable: */
+			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
+
+			/* driver argument */
+			xp=xNew<double>(num_independents);
+			for(i=0;i<num_independents;i++){
+				xp[i]=reCast<double,IssmDouble>(axp[i]);
+			}
+
+			/*get the EDF pointer:*/
+			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+			/*Branch according to AD driver: */
+			femmodel->parameters->FindParam(&driver,AutodiffDriverEnum);
+
+			/* these are always needed regardless of the interpreter */
+			anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
+			anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+			if (strcmp(driver,"fos_forward")==0){ /*{{{*/
+
+				int     anIndepIndex;
+				double *tangentDir         = NULL;
+				double *jacTimesTangentDir = NULL;
+				double *theOutput          = NULL;
+
+				/*retrieve direction index: */
+				femmodel->parameters->FindParam(&anIndepIndex,AutodiffFosForwardIndexEnum);
+
+				if (anIndepIndex<0 || anIndepIndex>=num_independents) _error_("index value for AutodiffFosForwardIndexEnum should be in [0,num_independents-1]");
+
+				tangentDir=xNewZeroInit<double>(num_independents);
+				tangentDir[anIndepIndex]=1.0;
+
+				jacTimesTangentDir=xNew<double>(num_dependents);
+				theOutput=xNew<double>(num_dependents);
+
+				/*set the forward method function pointer: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
+				anEDF_for_solverx_p->dp_X=xNew<double>(anEDF_for_solverx_p->max_n);
+				anEDF_for_solverx_p->dp_Y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+				/*call driver: */
+				fos_forward(my_rank,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,jacTimesTangentDir,num_dependents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(theOutput);
+				xDelete(jacTimesTangentDir);
+				xDelete(tangentDir);
+			} /*}}}*/
+			else if ((strcmp(driver,"fov_forward")==0) || (strcmp(driver,"fov_forward_all")==0)){ /*{{{*/
+
+				int      tangentDirNum;
+				int      dummy;
+				int     *indepIndices  = NULL;
+				double **jacTimesSeed  = NULL;
+				double **seed          = NULL;
+				double  *theOutput     = NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_forward_all")==0){
+					tangentDirNum=num_independents;
+					indepIndices=xNewZeroInit<int>(tangentDirNum);
+					for(i=0;i<num_independents;i++)indepIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&indepIndices,&tangentDirNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (tangentDirNum<1 || tangentDirNum>num_independents) _error_("tangentDirNum should be in [1,num_independents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				jacTimesSeed=xNew<double>(num_dependents,tangentDirNum);
+
+				/*set the forward method function pointers: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+#endif
+				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke EDF fov_forward:*/
+				anEDF_for_solverx_p->dpp_X=xNew<double>(anEDF_for_solverx_p->max_n, tangentDirNum);
+				anEDF_for_solverx_p->dpp_Y=xNew<double>(anEDF_for_solverx_p->max_m, tangentDirNum);
+
+				/*seed matrix: */
+				seed=xNewZeroInit<double>(num_independents,tangentDirNum);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<tangentDirNum; ++i) {
+					/* make sure the index is in range*/
+					if (indepIndices[i]>num_independents) {
+						_error_("indepIndices values must be in [0,num_independents-1]");
+					}
+					if (anIndexSet.find(indepIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate indepIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(indepIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					seed[indepIndices[i]][i]=1.0;
+				}
+
+				/*allocate output: */
+				theOutput=xNew<double>(num_dependents);
+
+				/*call driver: */
+				fov_forward(my_rank,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
+				/*Free resources: */
+				xDelete(theOutput);
+				xDelete(indepIndices);
+				xDelete(seed);
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*jacTimesSeed,num_dependents*tangentDirNum,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(jacTimesSeed);
+				xDelete(indepIndices);
+			} /*}}}*/
+			else if (strcmp(driver,"fos_reverse")==0) { /*{{{*/
+
+				int     aDepIndex=0;
+				double *aWeightVector=NULL;
+				double *weightVectorTimesJac=NULL;
+
+				/*retrieve direction index: */
+				femmodel->parameters->FindParam(&aDepIndex,AutodiffFosReverseIndexEnum);
+				aWeightVector=xNewZeroInit<double>(num_dependents);
+				if (my_rank==0) {
+					if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
+					aWeightVector[aDepIndex]=1.0;
+				}
+				weightVectorTimesJac=xNew<double>(num_independents);
+
+				/*set the forward method function pointer: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+#endif
+#ifdef _HAVE_MUMPS_
+				anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
+#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dp_U=xNew<double>(anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dp_Z=xNew<double>(anEDF_for_solverx_p->max_n);
+
+				/*call driver: */
+				fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+				if(VerboseAutodiff())_printf0_("   done with fos_reverse\n");
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,weightVectorTimesJac,num_independents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(weightVectorTimesJac);
+				xDelete(aWeightVector);
+			} /*}}}*/
+			else if ((strcmp(driver,"fov_reverse")==0) || (strcmp(driver,"fov_reverse_all")==0)){ /*{{{*/
+
+				int* depIndices=NULL;
+				int weightNum;
+				int dummy;
+				double **weightsTimesJac=NULL;
+				double **weights=NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_reverse_all")==0){
+					weightNum=num_dependents;
+					depIndices=xNewZeroInit<int>(weightNum);
+					for(i=0;i<num_dependents;i++)depIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&depIndices,&weightNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (weightNum<1 || weightNum>num_dependents) _error_("tangentDirNum should be in [1,num_dependents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				weightsTimesJac=xNew<double>(weightNum,num_independents);
+
+				/*set the forward method function pointers: */
+				#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+				#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dpp_U=xNew<double>(weightNum,anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dpp_Z=xNew<double>(weightNum,anEDF_for_solverx_p->max_n);
+
+				/*seed matrix: */
+				weights=xNewZeroInit<double>(weightNum,num_dependents);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<weightNum; ++i) {
+					/* make sure the index is in range*/
+					if (depIndices[i]>num_dependents) {
+						_error_("depIndices values must be in [0,num_dependents-1]");
+					}
+					if (anIndexSet.find(depIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate depIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(depIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					weights[depIndices[i]][i]=1.0;
+				}
+
+				/*call driver: */
+				fov_reverse(my_rank,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*weightsTimesJac,weightNum*num_independents,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(weights);
+				xDelete(weightsTimesJac);
+				xDelete(depIndices);
+			} /*}}}*/
+			else _error_("driver: " << driver << " not yet supported!");
+
+			/* delete the allocated space for the parameters:*/
+			xDelete(anEDF_for_solverx_p->dp_x);
+			xDelete(anEDF_for_solverx_p->dp_X);
+			xDelete(anEDF_for_solverx_p->dpp_X);
+			xDelete(anEDF_for_solverx_p->dp_y);
+			xDelete(anEDF_for_solverx_p->dp_Y);
+			xDelete(anEDF_for_solverx_p->dpp_Y);
+			xDelete(anEDF_for_solverx_p->dp_U);
+			xDelete(anEDF_for_solverx_p->dpp_U);
+			xDelete(anEDF_for_solverx_p->dp_Z);
+			xDelete(anEDF_for_solverx_p->dpp_Z);
+
+			if(VerboseAutodiff())_printf0_("   end AD core\n");
+
+			/*Free resources: */
+			xDelete(xp);
+			xDelete(axp); 
+			xDelete(driver);
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/cores/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/adjointbalancethickness_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/adjointbalancethickness_core.cpp	(revision 16560)
@@ -0,0 +1,39 @@
+/*!\file:  adjointbalancethickness_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointbalancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*compute thickness */
+	if(VerboseSolution()) _printf0_("   computing thickness\n");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[1] = {AdjointEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+	}
+}
Index: /issm/trunk/src/c/cores/adjointstressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/adjointstressbalance_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/adjointstressbalance_core.cpp	(revision 16560)
@@ -0,0 +1,48 @@
+/*!\file:  adjointstressbalance_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointstressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool isFS;
+	bool save_results;
+	bool conserve_loads   = true;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*Compute velocities*/
+	if(VerboseSolution()) _printf0_("   computing velocities\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	solutionsequence_nonlinear(femmodel,conserve_loads); 
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*Compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum,AdjointHorizAnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results || true){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		if (isFS){
+			int outputs[4] = {AdjointxEnum,AdjointyEnum,AdjointzEnum,AdjointpEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
+		}
+		else{
+			int outputs[2] = {AdjointxEnum,AdjointyEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+		}
+	}
+}
Index: /issm/trunk/src/c/cores/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/balancethickness_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/balancethickness_core.cpp	(revision 16560)
@@ -0,0 +1,32 @@
+/*!\file: balancethickness_core.cpp
+ * \brief: core of the balancethickness solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs = ThicknessEnum;
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+	}
+
+}
Index: /issm/trunk/src/c/cores/balancevelocity_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/balancevelocity_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/balancevelocity_core.cpp	(revision 16560)
@@ -0,0 +1,37 @@
+/*!\file: balancevelocity_core.cpp
+ * \brief: core of the balancevelocity solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancevelocity_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing smoothed slopes:\n");
+	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeXAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeYAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	//surfaceslope_core(femmodel);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	femmodel->SetCurrentConfiguration(BalancevelocityAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[3] = {SurfaceSlopeXEnum,SurfaceSlopeYEnum,VelEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+	}
+
+}
Index: /issm/trunk/src/c/cores/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/bedslope_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/bedslope_core.cpp	(revision 16560)
@@ -0,0 +1,47 @@
+/*!\file: bedslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void bedslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+	int  meshtype;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&meshtype,MeshTypeEnum);
+
+	if(VerboseSolution()) _printf0_("   computing slope\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(L2ProjectionBaseAnalysisEnum);
+
+	femmodel->parameters->SetParam(BedSlopeXEnum,InputToL2ProjectEnum);
+	solutionsequence_linear(femmodel);
+
+	if(meshtype!=Mesh2DverticalEnum){
+		femmodel->parameters->SetParam(BedSlopeYEnum,InputToL2ProjectEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		if(meshtype!=Mesh2DverticalEnum){
+			int outputs[2] = {BedSlopeXEnum,BedSlopeYEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+		}
+		else{
+			int outputs[1] = {BedSlopeXEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+		}
+	}
+
+}
Index: /issm/trunk/src/c/cores/control_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/control_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/control_core.cpp	(revision 16560)
@@ -0,0 +1,129 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+bool controlconvergence(IssmDouble J, IssmDouble tol_cm);
+
+void control_core(FemModel* femmodel){
+
+	int     i;
+
+	/*parameters: */
+	int        num_controls;
+	int        nsteps;
+	IssmDouble tol_cm;
+	int        solution_type;
+	bool       isFS;
+	bool       dakota_analysis = false;
+
+	int        *control_type   = NULL;
+	IssmDouble *maxiter        = NULL;
+	IssmDouble *cm_jump        = NULL;
+
+	/*intermediary: */
+	IssmDouble search_scalar = 1.;
+	OptArgs    optargs;
+	OptPars    optpars;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*) = NULL;
+	void (*adjointcore)(FemModel*)  = NULL;
+
+	/*output: */
+	IssmDouble* J=NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,NULL,InversionMaxiterPerStepEnum);
+	femmodel->parameters->FindParam(&cm_jump,NULL,InversionStepThresholdEnum);
+	femmodel->parameters->FindParam(&tol_cm,InversionCostFunctionThresholdEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*out of solution_type, figure out solution core and adjoint function pointer*/
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+
+	/*Launch once a complete solution to set up all inputs*/
+	if(VerboseControl()) _printf0_("   preparing initial solution\n");
+	if(isFS) solutioncore(femmodel);
+
+	/*Initialize cost function: */
+	J=xNew<IssmDouble>(nsteps);
+
+	/*Initialize some of the BrentSearch arguments: */
+	optargs.femmodel=femmodel;
+	optpars.xmin=0; optpars.xmax=1;
+
+	/*Start looping: */
+	for(int n=0;n<nsteps;n++){
+
+		/*Display info*/
+		if(VerboseControl()) _printf0_("\n" << "   control method step " << n+1 << "/" << nsteps << "\n");
+
+
+		/*In steady state inversion, compute new temperature field now*/
+		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
+
+		if(VerboseControl()) _printf0_("   compute adjoint state:\n");
+		adjointcore(femmodel);
+		gradient_core(femmodel,n,search_scalar==0.);
+
+		if(VerboseControl()) _printf0_("   optimizing along gradient direction\n");
+		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
+		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
+
+		if(VerboseControl()) _printf0_("   updating parameter using optimized search scalar\n"); //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;
+	}
+
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	solutioncore(femmodel);
+
+	/*some results not computed by steadystate_core or stressbalance_core: */
+	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
+		femmodel->OutputControlsx(&femmodel->results);
+
+		#ifdef _HAVE_ADOLC_
+		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
+		for(i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
+		xDelete<IssmPDouble>(J_passive);
+		#else
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
+		#endif
+	}
+
+	/*Free ressources: */
+	xDelete<int>(control_type);
+	xDelete<IssmDouble>(maxiter);
+	xDelete<IssmDouble>(cm_jump);
+	xDelete<IssmDouble>(J);
+}
+bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
+
+	bool converged=false;
+
+	/*Has convergence been reached?*/
+	if (!xIsNan<IssmDouble>(tol_cm) && J<tol_cm){
+		converged=true;
+		if(VerboseConvergence()) _printf0_("      Convergence criterion reached: J = " << J << " < " << tol_cm);
+	}
+
+	return converged;
+}
Index: /issm/trunk/src/c/cores/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controltao_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/controltao_core.cpp	(revision 16560)
@@ -0,0 +1,179 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+#include <config.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
+#include <tao.h>
+
+/*Local prototype*/
+int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
+int IssmMonitor(TaoSolver,void*);
+typedef struct {
+	FemModel* femmodel;
+	double*   J;
+} AppCtx;
+
+void controltao_core(FemModel* femmodel){
+
+	/*TAO*/
+	int                 ierr;
+	int                 num_controls,solution_type;
+	int                 nsteps,maxiter;
+	AppCtx              user;
+	TaoSolver           tao = 0;
+	int                *control_list = NULL;
+	Vector<IssmDouble> *X            = NULL;
+	Vector<IssmDouble> *G            = NULL;
+	Vector<IssmDouble> *XL           = NULL;
+	Vector<IssmDouble> *XU           = NULL;
+
+	/*Initialize TAO*/
+	int argc; char **args=NULL;
+	PetscGetArgs(&argc,&args);
+	ierr = TaoInitialize(&argc,&args,(char*)0,"");
+	if(ierr) _error_("Could not initialize Tao");
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_list,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	maxiter=nsteps*10;
+
+	/*Prepare Toolkit*/
+	ToolkitsOptionsFromAnalysis(femmodel->parameters,DefaultAnalysisEnum);
+
+	/*Initialize TAO*/
+	TaoCreate(IssmComm::GetComm(),&tao);
+	if(VerboseControl()) _printf0_("   Initializing the Toolkit for Advanced Optimization (TAO)\n");
+	TaoSetFromOptions(tao);
+	TaoSetType(tao,"tao_blmvm");
+	//TaoSetType(tao,"tao_cg");
+	//TaoSetType(tao,"tao_lmvm");
+
+	/*Prepare all TAO parameters*/
+	TaoSetMonitor(tao,IssmMonitor,&user,NULL);
+	TaoSetMaximumFunctionEvaluations(tao,maxiter);
+	TaoSetMaximumIterations(tao,nsteps);
+	TaoSetTolerances(tao,0.,0.,0.,0.,0.);
+
+	GetVectorFromControlInputsx(&X, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	TaoSetInitialVector(tao,X->pvector->vector);
+	TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
+	delete XL;
+	delete XU;
+
+	user.J=xNewZeroInit<double>(maxiter+5);
+	user.femmodel=femmodel;
+	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
+
+	/*Solver optimization problem*/
+	if(VerboseControl()) _printf0_("   Starting optimization\n");
+	TaoSolve(tao);
+	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
+
+	/*Save results*/
+	TaoGetSolutionVector(tao,&X->pvector->vector);
+	G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
+	TaoGetGradientVector(tao,&G->pvector->vector);
+	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+	femmodel->OutputControlsx(&femmodel->results);
+	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
+
+	/*Finalize*/
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Clean up and return*/
+	xDelete<int>(control_list);
+	xDelete<double>(user.J);
+	delete X;
+	TaoDestroy(&tao);
+	TaoFinalize();
+}
+int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *userCtx){
+
+	/*Retreive arguments*/
+	int                  solution_type;
+	AppCtx              *user            = (AppCtx *)userCtx;
+	FemModel            *femmodel        = user->femmodel;
+	Vector<IssmDouble>  *gradient        = NULL;
+	Vector<IssmDouble>  *X               = NULL;
+
+	/*Convert input to Vec*/
+	X=new Vector<IssmDouble>(Xpetsc);
+
+	/*Set new variable*/
+	//VecView(X,PETSC_VIEWER_STDOUT_WORLD);
+	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	delete X;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute solution and adjoint*/
+	void (*solutioncore)(FemModel*)=NULL;
+	void (*adjointcore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	solutioncore(femmodel);
+	adjointcore(femmodel);
+
+	/*Compute objective function*/
+	femmodel->CostFunctionx(fcn);
+
+	/*Compute gradient*/
+	Gradjx(&gradient,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	VecCopy(gradient->pvector->vector,G); delete gradient;
+	VecScale(G,-1.);
+
+	/*Clean-up and return*/
+	return 0;
+}
+int IssmMonitor(TaoSolver tao, void *userCtx){
+
+	int         its,num_responses;
+	IssmDouble  f,gnorm,cnorm,xdiff;
+	AppCtx     *user      = (AppCtx *)userCtx;
+	FemModel   *femmodel  = user->femmodel;
+	int        *responses = NULL;
+
+	femmodel->parameters->FindParam(&responses,&num_responses,InversionCostFunctionsEnum);
+
+	TaoGetSolutionStatus(tao, &its, &f, &gnorm, &cnorm, &xdiff, NULL);
+	if(its==0) _printf0_("Iter       Function      Residual  |  List of contributions\n");
+	if(its==0) _printf0_("___________________________________________________________\n");
+	_printf0_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
+	user->J[its]=f;
+
+	/*Retrieve objective functions independently*/
+	for(int i=0;i<num_responses;i++){
+		femmodel->Responsex(&f,EnumToStringx(responses[i]));
+		_printf0_(" "<<setw(12)<<setprecision(7)<<f);
+	}
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<int>(responses);
+	return 0;
+}
+
+#else
+void controltao_core(FemModel* femmodel){
+	_error_("TAO not installed or PETSc version not supported");
+}
+#endif //_HAVE_TAO_ 
Index: /issm/trunk/src/c/cores/cores.h
===================================================================
--- /issm/trunk/src/c/cores/cores.h	(revision 16560)
+++ /issm/trunk/src/c/cores/cores.h	(revision 16560)
@@ -0,0 +1,60 @@
+/*
+ * cores.h: 
+ */
+
+#ifndef _CORES_H_
+#define _CORES_H_
+
+/*forward declarations: */
+struct OptArgs;
+class FemModel;
+class Parameters;
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+
+#include "../shared/io/Comm/IssmComm.h"
+#include "../shared/Numerics/types.h"
+
+/*cores: */
+void adjointstressbalance_core(FemModel* femmodel);
+void adjointbalancethickness_core(FemModel* femmodel);
+void gradient_core(FemModel* femmodel,int n=0,bool orthogonalize=false);
+void stressbalance_core(FemModel* femmodel);
+void hydrology_core(FemModel* femmodel);
+void thermal_core(FemModel* femmodel);
+void surfaceslope_core(FemModel* femmodel);
+void bedslope_core(FemModel* femmodel);
+void meshdeformation_core(FemModel* femmodel);
+void control_core(FemModel* femmodel);
+void controltao_core(FemModel* femmodel);
+void masstransport_core(FemModel* femmodel);
+void extrudefrombase_core(FemModel* femmodel);
+void extrudefromtop_core(FemModel* femmodel);
+void balancethickness_core(FemModel* femmodel);
+void balancevelocity_core(FemModel* femmodel);
+void slopecompute_core(FemModel* femmodel);
+void steadystate_core(FemModel* femmodel);
+void transient_core(FemModel* femmodel);
+void dakota_core(FemModel* femmodel);
+void ad_core(FemModel* femmodel);
+void dummy_core(FemModel* femmodel);
+void gia_core(FemModel* femmodel);
+void damage_core(FemModel* femmodel);
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
+
+//optimization
+int GradJSearch(IssmDouble* search_vector,FemModel* femmodel,int step);
+
+//diverse
+void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ptoolkitsname,char** plockname,char** prootpath,int argc,char **argv);
+void WriteLockFile(char* filename);
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
+void PrintBanner(void);
+
+//solution configuration
+void AnalysisConfiguration(int** pcores,int* pnumcores, int solutiontype);
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
+
+#endif
Index: /issm/trunk/src/c/cores/dakota_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/dakota_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/dakota_core.cpp	(revision 16560)
@@ -0,0 +1,230 @@
+/*!\file:  dakota_core.cpp
+ * \brief: wrapper to the Dakota capabilities. qmu fires up Dakota, and registers a Dakota Pluggin
+ * which will be in charge of running the solution sequences repeteadly, to garner statistics. 
+ *
+ * This routine deals with running ISSM and Dakota in library mode. In library mode, Dakota does not 
+ * run as an execuatble. Its capabilities are linked into the ISSM software. ISSM calls dakota routines 
+ * directly from the dakota library. qmu.cpp is the code that is in charge of calling those routines. 
+ *
+ * Dakota has its own way of running in parallel (for embarassingly parallel jobs). We do not want that, 
+ * as ISSM knows exactly how to run "really parallel" jobs that use all CPUS. To bypass Dakota's parallelism, 
+ * we overloaded the constructor for the parallel library (see the Dakota patch in the externalpackages/dakota
+ * directory). This overloaded constructor fires up Dakota serially on CPU 0 only! We take care of broadcasting 
+ * to the other CPUS, hence ISSM is running in parallel, and Dakota serially on CPU0. 
+ *
+ * Now, how does CPU 0 drive all other CPUS to carry out sensitivity analysese? By synchronizing its call to 
+ * our ISSM cores (stressbalance_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
+ * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up DakotaSpawnCore.cpp, 
+ * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
+ * DakotaSpawnCore. In the end, DakotaSpawnCore is fired up on all CPUS, with CPU0 having Dakota inputs, that it will 
+ * broacast to other CPUS. 
+ *
+ * Now, how does dakota call the DakotaSpawnCore routine? The DakotaSpawnCore is embedded into the DakotaPlugin object 
+ * which is derived from the Direct Interface Dakota objct. This is the only way to run Dakota in library 
+ * mode (see their developper guide for more info). Dakota registers the DakotaPlugin object into its own 
+ * database, and calls on the embedded DakotaSpawnCore from CPU0. 
+ *
+ */ 
+
+/*include files: {{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+#include "../classes/classes.h"
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <ParallelLibrary.H>
+#include <ProblemDescDB.H>
+#include <DakotaStrategy.H>
+#include <DakotaModel.H>
+#include <DakotaInterface.H>
+#else
+#include <ParallelLibrary.hpp>
+#include <ProblemDescDB.hpp>
+#include <DakotaStrategy.hpp>
+#include <DakotaModel.hpp>
+#include <DakotaInterface.hpp>
+#endif
+#include "./DakotaSpawnCore.h"
+#endif
+/*}}}*/
+/*DakotaPlugin class {{{*/
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <DirectApplicInterface.H>
+#include <DakotaResponse.H>
+#include <ParamResponsePair.H>
+#include <system_defs.h>
+#include <ProblemDescDB.H>
+#include <ParallelLibrary.H>
+#else
+#include <DirectApplicInterface.hpp>
+#include <DakotaResponse.hpp>
+#include <ParamResponsePair.hpp>
+#include <ProblemDescDB.hpp>
+#include <ParallelLibrary.hpp>
+#endif
+namespace SIM {
+	class DakotaPlugin: public Dakota::DirectApplicInterface{
+		public:
+			/*these fields are used by core solutions: */
+			void *femmodel;
+			int   counter;
+			/*Constructors/Destructors*/
+			DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){/*{{{*/
+				femmodel = in_femmodel;
+				counter  = 0;
+			}/*}}}*/
+			~DakotaPlugin(){/*{{{*/
+				/* Virtual destructor handles referenceCount at Interface level. */ 
+			}/*}}}*/
+		protected:
+			/*execute the input filter portion of a direct evaluation invocation*/
+			//int derived_map_if(const Dakota::String& if_name);
+			/*execute an analysis code portion of a direct evaluation invocation*/
+			int derived_map_ac(const Dakota::String& driver){/*{{{*/
+
+				int i;
+				IssmDouble* variables=NULL;
+				char** variable_descriptors=NULL;
+				char*  variable_descriptor=NULL;
+				IssmDouble* responses=NULL;
+
+				/*increae counter: */
+				counter++;
+
+				/*Before launching analysis, we need to transfer the dakota inputs into Issm 
+				 *readable variables: */
+
+				/*First, the variables: */
+				variables=xNew<IssmDouble>(numACV);
+				for(i=0;i<numACV;i++){
+					variables[i]=xC[i];
+				}
+				/*The descriptors: */
+				variable_descriptors=xNew<char*>(numACV);
+				for(i=0;i<numACV;i++){
+					std::string label=xCLabels[i];
+					variable_descriptor=xNew<char>(strlen(label.c_str())+1);
+					memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
+
+					variable_descriptors[i]=variable_descriptor;
+				}
+
+				/*Initialize responses: */
+				responses=xNewZeroInit<IssmDouble>(numFns);
+
+				/*run core solution: */
+				DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
+
+				/*populate responses: */
+				for(i=0;i<numFns;i++){
+					fnVals[i]=responses[i];
+				}
+
+				/*Free ressources:*/
+				xDelete<IssmDouble>(variables);
+				for(i=0;i<numACV;i++){
+					variable_descriptor=variable_descriptors[i];
+					xDelete<char>(variable_descriptor);
+				}
+				xDelete<char*>(variable_descriptors);
+				xDelete<IssmDouble>(responses);
+
+				return 0;
+			}/*}}}*/
+			/*execute the output filter portion of a direct evaluation invocation*/
+			//int derived_map_of(const Dakota::String& of_name);
+			/*add for issm: */
+			int GetCounter(){/*{{{*/
+				return counter;
+			}/*}}}*/
+		private:
+	};
+} 
+#endif
+/*}}}*/
+
+void dakota_core(FemModel* femmodel){ 
+
+	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+	int                my_rank;
+	char              *dakota_input_file  = NULL;
+	char              *dakota_output_file = NULL;
+	char              *dakota_error_file  = NULL;
+	Dakota::ModelLIter ml_iter;
+
+	/*Recover dakota_input_file, dakota_output_file and dakota_error_file, in the parameters dataset in parallel */
+	femmodel->parameters->FindParam(&dakota_input_file,QmuInNameEnum);
+	femmodel->parameters->FindParam(&dakota_output_file,QmuOutNameEnum);
+	femmodel->parameters->FindParam(&dakota_error_file,QmuErrNameEnum);
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+
+		// Instantiate/initialize the parallel library and problem description
+		// database objects.
+		char* dakotamode=xNew<char>(strlen("serial")+1);
+		xMemCpy<char>(dakotamode,"serial",strlen("serial")+1);
+		Dakota::ParallelLibrary parallel_lib(dakotamode); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
+		Dakota::ProblemDescDB problem_db(parallel_lib); 
+		xDelete<char>(dakotamode);
+
+		// Manage input file parsing, output redirection, and restart processing
+		// without a CommandLineHandler.  This version relies on parsing of an
+		// input file.
+		problem_db.manage_inputs(dakota_input_file);
+		// specify_outputs_restart() is only necessary if specifying non-defaults
+		parallel_lib.specify_outputs_restart(dakota_output_file,dakota_error_file,NULL,NULL);
+
+		// Instantiate the Strategy object (which instantiates all Model and
+		// Iterator objects) using the parsed information in problem_db.
+		Dakota::Strategy selected_strategy(problem_db);
+
+		// convenience function for iterating over models and performing any
+		// interface plug-ins
+		Dakota::ModelList& models = problem_db.model_list();
+
+		for (ml_iter = models.begin(); ml_iter != models.end(); ml_iter++) {
+
+			Dakota::Interface& interface = ml_iter->interface();
+
+			//set DB nodes to the existing Model specification
+			problem_db.set_db_model_nodes(ml_iter->model_id());
+
+			// Serial case: plug in derived Interface object without an analysisComm
+			interface.assign_rep(new SIM::DakotaPlugin(problem_db,(void*)femmodel), false);
+		}
+
+		// Execute the strategy
+		problem_db.lock(); // prevent run-time DB queries
+		selected_strategy.run_strategy();
+
+		//Warn other cpus that we are done running the dakota iterator, by setting the counter to -1:
+		DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,-1);
+
+	}
+	else{
+
+		for(;;){
+			if(!DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,0))break; //counter came in at -1 on cpu0, bail out.
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<char>(dakota_input_file);
+	xDelete<char>(dakota_error_file);
+	xDelete<char>(dakota_output_file);
+
+	#endif //#ifdef _HAVE_DAKOTA_
+}
Index: /issm/trunk/src/c/cores/damage_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/damage_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/damage_core.cpp	(revision 16560)
@@ -0,0 +1,39 @@
+/* 
+ * \brief: damgage_core.cpp: core for the damage solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void damage_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results;
+	bool   dakota_analysis  = false;
+	int    solution_type;
+
+	if(VerboseSolution()) _printf0_("   computing damage\n");
+	
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	if(dakota_analysis && solution_type!=TransientSolutionEnum){
+		femmodel->SetCurrentConfiguration(DamageEvolutionAnalysisEnum);
+		ResetConstraintsx(femmodel);
+	}
+
+	femmodel->SetCurrentConfiguration(DamageEvolutionAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs = DamageDEnum;
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+	}
+}
Index: /issm/trunk/src/c/cores/dummy_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/dummy_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/dummy_core.cpp	(revision 16560)
@@ -0,0 +1,11 @@
+/*!\file: dummy_core.cpp
+ * \brief: dummy core (nothing done)
+ */ 
+
+class FemModel;
+
+void dummy_core(FemModel* femmodel){
+
+	/*We do not do anything*/
+
+}
Index: /issm/trunk/src/c/cores/extrudefrombase_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 16560)
@@ -0,0 +1,21 @@
+/*!\file: extrudefrombase_core.cpp
+ * \brief: core of the extrusion solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void extrudefrombase_core(FemModel* femmodel){
+
+	if(VerboseSolution()) _printf0_("extruding solution from base...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(ExtrudeFromBaseAnalysisEnum);
+	femmodel->UpdateConstraintsExtrudeFromBasex();
+	solutionsequence_linear(femmodel);
+
+}
Index: /issm/trunk/src/c/cores/extrudefromtop_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 16560)
@@ -0,0 +1,21 @@
+/*!\file: extrudefromtop_core.cpp
+ * \brief: core of the extrusion solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void extrudefromtop_core(FemModel* femmodel){
+
+	if(VerboseSolution()) _printf0_("extruding solution from top...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(ExtrudeFromTopAnalysisEnum);
+	femmodel->UpdateConstraintsExtrudeFromTopx();
+	solutionsequence_linear(femmodel);
+
+}
Index: /issm/trunk/src/c/cores/gia_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/gia_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/gia_core.cpp	(revision 16560)
@@ -0,0 +1,56 @@
+/*!\file: gia_core.cpp
+ * \brief: core of the GIA solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+void gia_core(FemModel* femmodel){
+
+	Vector<IssmDouble> *wg    = NULL;
+	Vector<IssmDouble> *dwdtg = NULL;
+	IssmDouble          *x    = NULL;
+	IssmDouble          *y    = NULL;
+
+	/*parameters: */
+	bool save_results;
+	int  gsize;
+	int  configuration_type;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	if(VerboseSolution()) _printf0_("   computing GIA\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(GiaAnalysisEnum);
+
+	/*Figure out size of g-set deflection vector and allocate solution vector: */
+	gsize      = femmodel->nodes->NumberOfDofs(configuration_type,GsetEnum);
+	wg = new Vector<IssmDouble>(gsize);
+	dwdtg = new Vector<IssmDouble>(gsize);
+
+	/*first, recover x and y vectors from vertices: */
+	VertexCoordinatesx(&x,&y,NULL,femmodel->vertices); //no need for z coordinate
+
+	/*call the main module: */
+	femmodel->Deflection(wg,dwdtg,x,y);
+
+	/*assemble vector: */
+	wg->Assemble();
+	dwdtg->Assemble();
+
+	InputUpdateFromVectorx(femmodel,wg,GiaWEnum,VertexSIdEnum);
+	InputUpdateFromVectorx(femmodel,dwdtg,GiadWdtEnum,VertexSIdEnum);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		const int outputs[2] = {GiaWEnum,GiadWdtEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+	}
+
+}
Index: /issm/trunk/src/c/cores/gradient_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/gradient_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/gradient_core.cpp	(revision 16560)
@@ -0,0 +1,48 @@
+/*!\file:  gradient_core.cpp
+ * \brief compute inverse method gradient direction.
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void gradient_core(FemModel* femmodel,int step,bool orthogonalize){ 
+
+	/*Intermediaries*/
+	IssmDouble  norm_inf;
+	IssmDouble *norm_list    = NULL;
+	Vector<IssmDouble>*     new_gradient = NULL;
+	Vector<IssmDouble>*     gradient     = NULL;
+	Vector<IssmDouble>*     old_gradient = NULL;
+
+	/*Compute gradient*/
+	if(VerboseControl()) _printf0_("   compute cost function gradient\n");
+	Gradjx(&gradient,&norm_list,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
+
+	if (orthogonalize){
+		if(VerboseControl()) _printf0_("   orthogonalization\n");
+		ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
+		Orthx(&new_gradient,gradient,old_gradient); delete old_gradient; delete gradient;
+	}
+	else{ 
+		new_gradient=gradient;
+	}
+
+	/*Check that gradient is clean*/
+	norm_inf=new_gradient->Norm(NORM_INF);
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+
+	/*plug back into inputs: */
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,new_gradient);
+	delete new_gradient;
+
+	/*Scale Gradients*/
+	ControlInputScaleGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,norm_list,step);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(norm_list);
+}
Index: /issm/trunk/src/c/cores/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/hydrology_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/hydrology_core.cpp	(revision 16560)
@@ -0,0 +1,105 @@
+/*!\file: hydrology_core.cpp
+ * \brief: core of the hydrology solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void hydrology_core(FemModel* femmodel){
+
+	int i;
+
+	/*intermediary*/
+	int        step,nsteps;
+	int        output_frequency,hydrology_model;
+	bool       save_results;
+	bool       modify_loads=true;
+	bool       isefficientlayer;
+	IssmDouble starttime,final_time;
+	IssmDouble time,dt;
+
+	/*first recover parameters common to all solutions*/
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	femmodel->parameters->FindParam(&hydrology_model,HydrologyModelEnum);
+
+	/*first compute slopes: */
+	if (hydrology_model==HydrologyshreveEnum){
+		surfaceslope_core(femmodel);
+		bedslope_core(femmodel);
+	}
+
+	/*Compute number of time steps: */
+	if((dt==0)|| (final_time==0)){
+		dt=0;
+		nsteps=1;
+	}
+	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
+
+	/*initialize: */
+	step=0;
+	time=starttime;
+
+	/*Loop through time: */
+	for(i=0;i<nsteps;i++){
+
+		if(nsteps)if(VerboseSolution()) _printf0_("time step:" << i+1 << "/" << nsteps << "\n");
+		time+=dt;
+		step+=1;
+		femmodel->parameters->SetParam(time,TimeEnum);
+		femmodel->parameters->SetParam(step,StepEnum);
+
+		if (hydrology_model==HydrologyshreveEnum){
+			if(VerboseSolution()) _printf0_("   computing water column\n");
+			femmodel->SetCurrentConfiguration(HydrologyShreveAnalysisEnum);
+			solutionsequence_nonlinear(femmodel,modify_loads);
+
+			/*transfer water column thickness to old water column thickness: */
+
+			InputDuplicatex(femmodel,WatercolumnEnum,WaterColumnOldEnum);
+
+			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
+				if(VerboseSolution()) _printf0_("   saving results \n");
+				int outputs[3] = {WatercolumnEnum,HydrologyWaterVxEnum,HydrologyWaterVyEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+
+				/*unload results*/
+				if(VerboseSolution()) _printf0_("   saving temporary results\n");
+				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+			}
+		}
+
+		else if (hydrology_model==HydrologydcEnum){
+			InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+			femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+			if (isefficientlayer){
+				InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
+			}
+
+			if(VerboseSolution()) _printf0_("   computing water head\n");
+			solutionsequence_hydro_nonlinear(femmodel);
+			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
+				if(VerboseSolution()) _printf0_("   saving results \n");
+				if(isefficientlayer){
+					int outputs[4] = {SedimentHeadEnum,SedimentHeadResidualEnum,EplHeadEnum,HydrologydcMaskEplactiveEnum};
+					femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
+				}
+				else{
+					int outputs[2] = {SedimentHeadEnum,SedimentHeadResidualEnum};
+					femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+				}
+				/*unload results*/
+				if(VerboseSolution()) _printf0_("   saving temporary results\n");
+				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+			}
+		}
+
+	}
+}
Index: /issm/trunk/src/c/cores/masstransport_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/masstransport_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/masstransport_core.cpp	(revision 16560)
@@ -0,0 +1,87 @@
+/*!\file: masstransport_core.cpp
+ * \brief: core of the masstransport solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void masstransport_core(FemModel* femmodel){
+
+	/*parameters: */
+	int    i;
+	int    numoutputs,meshtype;
+	bool   save_results;
+	bool   issmbgradients,ispdd,isdelta18o,isFS,isfreesurface,dakota_analysis;
+	int    solution_type;
+	char** requested_outputs = NULL;
+
+	/*activate configuration*/
+	femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
+	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&isfreesurface,MasstransportIsfreesurfaceEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&meshtype,MeshTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==MasstransportSolutionEnum){
+		InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
+		InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
+		InputDuplicatex(femmodel,QmuBedEnum,BedEnum);
+	}
+
+	if(issmbgradients){
+	  if(VerboseSolution())_printf_("	call smb gradients module\n\n");
+	  SmbGradientsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+	if(ispdd){
+		if(isdelta18o){
+			if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
+			Delta18oParameterizationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		} 
+		if(VerboseSolution()) _printf0_("   call positive degree day module\n");
+		PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(isFS && isfreesurface){
+		if(VerboseSolution()) _printf0_("   call free surface computational core\n");
+		femmodel->SetCurrentConfiguration(FreeSurfaceBaseAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		if(meshtype==Mesh2DverticalEnum){
+			femmodel->parameters->SetParam(BedEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+		}
+		femmodel->SetCurrentConfiguration(FreeSurfaceTopAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		if(meshtype==Mesh2DverticalEnum){
+			femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
+			extrudefromtop_core(femmodel);
+		}
+	}
+	else{
+		if(VerboseSolution()) _printf0_("   call computational core\n");
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	if(solution_type==MasstransportSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	if(numoutputs){for(int i=0;i<numoutputs;i++){char* string=requested_outputs[i];xDelete<char>(string);} xDelete<char*>(requested_outputs);} 
+}
Index: /issm/trunk/src/c/cores/meshdeformation_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/meshdeformation_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/meshdeformation_core.cpp	(revision 16560)
@@ -0,0 +1,30 @@
+/*!\file: meshdeformation_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void meshdeformation_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing mesh deformation (elasticity)...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(MeshdeformationAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("saving results:\n");
+	}
+
+}
Index: /issm/trunk/src/c/cores/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/cores/objectivefunction.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/objectivefunction.cpp	(revision 16560)
@@ -0,0 +1,77 @@
+/*!\file:  objectivefunction
+ * \brief  objective function that returns a misfit, for a certain parameter.
+ */ 
+
+/*include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+/*}}}*/
+
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
+
+	/*output: */
+	IssmDouble J;
+
+	/*parameters: */
+	int        solution_type,analysis_type;
+	bool       isFS       = false;
+	bool       conserve_loads = true;
+	FemModel  *femmodel       = NULL;
+
+	/*Recover finite element model: */
+	femmodel=optargs->femmodel;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*set analysis type to compute velocity: */
+	if (solution_type==SteadystateSolutionEnum || solution_type==StressbalanceSolutionEnum){
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	}
+	else if (solution_type==BalancethicknessSoftSolutionEnum){
+		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	}
+	else{
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	}
+
+	/*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 stressbalance with updated inputs: */
+	if (solution_type==SteadystateSolutionEnum){
+		stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+	}
+	else if (solution_type==StressbalanceSolutionEnum){
+		solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		solutionsequence_linear(femmodel); 
+	}
+	else if (solution_type==BalancethicknessSoftSolutionEnum){
+		/*Don't do anything*/
+	}
+	else{
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	}
+
+	/*Compute misfit for this velocity field.*/
+	femmodel->CostFunctionx(&J);
+
+	/*Free ressources:*/
+	return J;
+}
Index: /issm/trunk/src/c/cores/steadystate_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/steadystate_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/steadystate_core.cpp	(revision 16560)
@@ -0,0 +1,130 @@
+/*!\file: steadystate_core.cpp
+ * \brief: core of the steadystate solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol);
+
+void steadystate_core(FemModel* femmodel){
+
+	/*intermediary: */
+	int i;
+	int step; 
+	Vector<IssmDouble>* ug     = NULL;
+	Vector<IssmDouble>* ug_old = NULL;
+	Vector<IssmDouble>* tg     = NULL;
+	Vector<IssmDouble>* tg_old = NULL;
+
+	/*parameters: */
+	bool        save_results,isenthalpy;
+	int         maxiter;
+	IssmDouble  reltol;
+	int         numoutputs        = 0;
+	char** requested_outputs = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&maxiter,SteadystateMaxiterEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	femmodel->parameters->FindParam(&reltol,SteadystateReltolEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	femmodel->parameters->FindParam(&numoutputs,SteadystateNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,SteadystateRequestedOutputsEnum);
+
+	/*intialize counters: */
+	step=1;
+
+	for(;;){
+
+		if(VerboseSolution()) _printf0_("   computing temperature and velocity for step: " << step << "\n");
+		#ifdef _HAVE_THERMAL_
+		thermal_core(femmodel);
+		if(!isenthalpy)femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);/*Could be MeltingAnalysis...*/
+		GetSolutionFromInputsx(&tg,femmodel);
+		#else
+		_error_("ISSM was not compiled with thermal capabilities. Exiting");
+		#endif
+
+		if(VerboseSolution()) _printf0_("   computing new velocity\n");
+		stressbalance_core(femmodel);
+		GetSolutionFromInputsx(&ug,femmodel);
+
+		if(step>1){
+			if(VerboseSolution()) _printf0_("   checking steadystate convergence\n");
+			if(steadystateconvergence(tg,tg_old,ug,ug_old,reltol)) break;
+		}
+		if(step>maxiter){
+			if(VerboseSolution()) _printf0_("   maximum number steadystate iterations " << maxiter << " reached\n");
+			break;
+		}
+
+		/*update results and increase counter*/
+		delete tg_old;tg_old=tg;
+		delete ug_old;ug_old=ug;
+		step++;
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/
+	delete tg_old;
+	delete ug_old;
+	delete tg;
+	delete ug;	
+	if(numoutputs){ for (i=0;i<numoutputs;i++){char* string=requested_outputs[i];xDelete<char>(string);} xDelete<char*>(requested_outputs);}
+}
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol){
+
+	/*Output*/
+	bool converged = true;
+
+	/*Intermediary*/
+	Vector<IssmDouble>* dug    = NULL;
+	Vector<IssmDouble>* dtg    = NULL;
+	IssmDouble          ndt,nt;
+	IssmDouble          ndu,nu;
+
+	/*compute norm(du)/norm(u)*/
+	dug=ug_old->Duplicate(); ug_old->Copy(dug); dug->AYPX(ug,-1.0);
+	ndu=dug->Norm(NORM_TWO); nu=ug_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+	if((ndu/nu)<reltol){
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*compute norm(dt)/norm(t)*/
+	dtg=tg_old->Duplicate(); tg_old->Copy(dtg); dtg->AYPX(tg,-1.0);
+	ndt=dtg->Norm(NORM_TWO); nt=tg_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndt) || xIsNan<IssmDouble>(nt)) _error_("convergence criterion is NaN!");
+	if((ndt/nt)<reltol){
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*clean up and return*/
+	delete dtg;
+	delete dug;
+	return converged;
+}
Index: /issm/trunk/src/c/cores/stressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 16560)
@@ -0,0 +1,97 @@
+/*!\file: stressbalance_core.cpp
+ * \brief: core of the stressbalance solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void stressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool  dakota_analysis;
+	int   meshtype;
+	bool  isSIA,isSSA,isL1L2,isHO,isFS;
+	bool  conserve_loads    = true;
+	bool  save_results;
+	int   newton;
+	int   solution_type;
+	int   numoutputs        = 0;
+	char** requested_outputs = NULL;
+	int    i;
+
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&meshtype,MeshTypeEnum);
+	femmodel->parameters->FindParam(&isSIA,FlowequationIsSIAEnum);
+	femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+	femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
+	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==StressbalanceSolutionEnum){
+		InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
+		InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
+		InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
+		if(isFS) InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
+	}
+
+	/*Compute slopes: */
+	if(isSIA) surfaceslope_core(femmodel);
+	if(isFS){
+		bedslope_core(femmodel);
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		ResetCoordinateSystemx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(isSIA){
+		if(VerboseSolution()) _printf0_("   computing SIA velocities\n");
+
+		/*Take the last velocity into account so that the velocity on the SSA domain is not zero*/
+		if(isSSA || isL1L2 || isHO ) ResetBoundaryConditions(femmodel,StressbalanceSIAAnalysisEnum);
+		femmodel->SetCurrentConfiguration(StressbalanceSIAAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		if(isSSA || isL1L2 || isHO) ResetBoundaryConditions(femmodel,StressbalanceAnalysisEnum);
+	}
+
+	if ((isSSA || isHO || isL1L2) ^ isFS){ // ^ = xor
+		if(VerboseSolution()) _printf0_("   computing velocities\n");
+
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		if(newton>0)
+		 solutionsequence_newton(femmodel);
+		else
+		 solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+
+	if ((isSSA || isL1L2 || isHO) && isFS){
+		if(VerboseSolution()) _printf0_("   computing coupling betweem lower order models and full-FS\n");
+		solutionsequence_FScoupling_nonlinear(femmodel,conserve_loads);
+	}
+
+	if (meshtype==Mesh3DEnum && (isSIA || isSSA || isL1L2 || isHO)){
+		if(VerboseSolution()) _printf0_("   computing vertical velocities\n");
+		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	if(solution_type==StressbalanceSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/	
+	if(numoutputs){ for (i=0;i<numoutputs;i++){char* string=requested_outputs[i];xDelete<char>(string);} xDelete<char*>(requested_outputs);}
+}
Index: /issm/trunk/src/c/cores/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/surfaceslope_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/surfaceslope_core.cpp	(revision 16560)
@@ -0,0 +1,48 @@
+/*!\file: surfaceslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void surfaceslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+	int  meshtype;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&meshtype,MeshTypeEnum);
+
+	if(VerboseSolution()) _printf0_("computing slope...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(L2ProjectionBaseAnalysisEnum);
+
+	femmodel->parameters->SetParam(SurfaceSlopeXEnum,InputToL2ProjectEnum);
+	solutionsequence_linear(femmodel);
+
+	if(meshtype!=Mesh2DverticalEnum){
+		femmodel->parameters->SetParam(SurfaceSlopeYEnum,InputToL2ProjectEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("saving results:\n");
+		if(meshtype!=Mesh2DverticalEnum){
+			int outputs[2] = {SurfaceSlopeXEnum,SurfaceSlopeYEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+
+		}
+		else{
+			int outputs = SurfaceSlopeXEnum;
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+		}
+	}
+
+}
Index: /issm/trunk/src/c/cores/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/thermal_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/thermal_core.cpp	(revision 16560)
@@ -0,0 +1,65 @@
+/*!\file: thermal_core.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void thermal_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results,isenthalpy;
+	bool   dakota_analysis;
+	int    solution_type,numoutputs;
+	char** requested_outputs = NULL;
+
+	/*first recover parameters common to all solutions*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	femmodel->parameters->FindParam(&numoutputs,ThermalNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,ThermalRequestedOutputsEnum);
+
+	if(dakota_analysis && solution_type!=TransientSolutionEnum){
+		InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
+		InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
+		InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
+		InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
+		InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
+		InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		ResetConstraintsx(femmodel);
+	}
+
+	if(isenthalpy){
+
+		if(VerboseSolution()) _printf0_("   computing enthalpy\n");
+		femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
+		solutionsequence_nonlinear(femmodel,true);
+
+		/*transfer enthalpy to enthalpy picard for the next step: */
+		InputDuplicatex(femmodel,EnthalpyEnum,EnthalpyPicardEnum);
+
+		/*Post process*/
+		if(solution_type!=SteadystateSolutionEnum) PostprocessingEnthalpyx(femmodel);
+	}
+	else{
+		if(VerboseSolution()) _printf0_("   computing temperatures\n");
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		solutionsequence_thermal_nonlinear(femmodel);
+
+		if(VerboseSolution()) _printf0_("   computing melting\n");
+		femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+}
Index: /issm/trunk/src/c/cores/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/transient_core.cpp	(revision 16560)
+++ /issm/trunk/src/c/cores/transient_core.cpp	(revision 16560)
@@ -0,0 +1,182 @@
+/*!\file: transient_3d_core.cpp
+ * \brief: core of the transient_3d solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <float.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void transient_core(FemModel* femmodel){
+
+	/*parameters: */
+	int    i;
+	IssmDouble starttime,finaltime,dt,yts;
+	bool   isstressbalance,ismasstransport,isFS,isthermal,isgroundingline,isdelta18o,isgia;
+	bool   save_results,dakota_analysis;
+	bool   time_adapt=false;
+	int    output_frequency;
+	int    meshtype,groundingline_migration;
+	int    numoutputs         = 0;
+	char** requested_outputs = NULL;
+
+
+	/*intermediary: */
+	int    step;
+	IssmDouble time;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&meshtype,MeshTypeEnum);
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
+	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
+	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
+	femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
+	femmodel->parameters->FindParam(&isgia,TransientIsgiaEnum);
+	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
+	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+
+	/*initialize: */
+	step=0;
+	time=starttime;
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis){
+		if(isstressbalance){
+			InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
+			InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
+			if(meshtype==Mesh3DEnum){
+				InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
+				if(isFS)InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
+			}
+		}
+		if(ismasstransport || isgroundingline){
+			InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
+			InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
+			InputDuplicatex(femmodel,QmuBedEnum,BedEnum);
+			InputDuplicatex(femmodel,QmuMaskIceLevelsetEnum,MaskIceLevelsetEnum);
+		}
+		if(isgroundingline) InputDuplicatex(femmodel,QmuMaskGroundediceLevelsetEnum,MaskGroundediceLevelsetEnum);
+		if(isthermal && meshtype==Mesh3DEnum){
+			//Update Vertex Position after updating Thickness and Bed
+			femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
+			femmodel->UpdateVertexPositionsx();
+			InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
+			InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
+			InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
+			InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
+			InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
+			InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
+			//Reset Thermal Constraints
+			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+			ResetConstraintsx(femmodel);
+		}
+	}
+
+	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
+
+		/*Increment*/
+		if(time_adapt){
+			femmodel->TimeAdaptx(&dt);
+			if(time+dt>finaltime) dt=finaltime-time;
+			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+		}
+		step+=1;
+		time+=dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+		femmodel->parameters->SetParam(step,StepEnum);
+
+		if(VerboseSolution()) _printf0_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << time/yts << " (time step: " << dt/yts << ")\n");
+		if(step%output_frequency==0 || time==finaltime)
+		 save_results=true;
+		else
+		 save_results=false;
+		femmodel->parameters->SetParam(save_results,SaveResultsEnum);
+
+		if(isthermal && meshtype==Mesh3DEnum){
+			if(VerboseSolution()) _printf0_("   computing temperatures\n");
+			#ifdef _HAVE_THERMAL_
+			thermal_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+		}
+
+		if(isstressbalance){
+			if(VerboseSolution()) _printf0_("   computing new velocity\n");
+			#ifdef _HAVE_STRESSBALANCE_
+			stressbalance_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with stressbalance capabilities. Exiting");
+			#endif
+		}
+
+		if(ismasstransport){
+			if(VerboseSolution()) _printf0_("   computing new thickness\n");
+			masstransport_core(femmodel);
+			if(VerboseSolution()) _printf0_("   updating vertices positions\n");
+			femmodel->UpdateVertexPositionsx();
+		}
+
+		if(isgroundingline){
+			if(VerboseSolution()) _printf0_("   computing new grounding line position\n");
+			#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
+			if(save_results){
+				int outputs[3] = {SurfaceEnum,BedEnum,MaskGroundediceLevelsetEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+			}
+		}
+		if(isgia){
+			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
+			#ifdef _HAVE_GIA_
+			gia_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with gia capabilities. Exiting");
+			#endif
+
+		}
+
+		/*unload results*/
+		if(save_results){
+			if(VerboseSolution()) _printf0_("   saving transient results\n");
+			femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+			if(isdelta18o){
+				int outputs[2] = {SurfaceforcingsMonthlytemperaturesEnum,SurfaceforcingsPrecipitationEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+			}
+			if(isgroundingline && (groundingline_migration==SubelementMigrationEnum || groundingline_migration==SubelementMigration2Enum)){
+				int outputs[1] = {MaskGroundediceLevelsetEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+			}
+			if(VerboseSolution()) _printf0_("   saving temporary results\n");
+			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+		}
+	}
+
+	femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/	
+	if(numoutputs){ for (i=0;i<numoutputs;i++){char* string=requested_outputs[i];xDelete<char>(string);} xDelete<char*>(requested_outputs);}
+}
Index: /issm/trunk/src/c/kml/KMLFileReadUtils.cpp
===================================================================
--- /issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 16560)
@@ -314,5 +314,5 @@
 
 	/*  return next non " =?/>" and move past subsequent " =?/>"  */
-	while (ktokn=strtok(NULL," =?/>")) {
+	while((ktokn=strtok(NULL," =?/>"))){
 
 		/*  return next non quote and move past subsequent quote  */
@@ -358,5 +358,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -365,6 +365,8 @@
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
 		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
-		else
+		else{
 			xDelete<char>(kstr);
+		}
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pival << ".\n");
@@ -392,5 +394,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -401,4 +403,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=" << (*pbval ? "true" : "false") << ".\n");
@@ -453,5 +456,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -462,4 +465,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=\"" << pstr << "\".\n");
@@ -487,5 +491,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -496,4 +500,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pfval << ".\n");
@@ -521,5 +526,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -530,4 +535,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pdval << ".\n");
@@ -554,9 +560,10 @@
 		_error_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
 
-	if (!*pdval)
+	if(!*pdval){
 		if (maxlen)
 			*pdval=xNew<IssmPDouble>(maxlen            );
 		else
 			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
+	}
 
 /*  loop through string to get all values  */
@@ -585,5 +592,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -594,4 +601,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
@@ -620,9 +628,10 @@
 		_error_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
 
-	if (!*pdval)
+	if(!*pdval){
 		if (maxlen)
 			*pdval=xNew<IssmPDouble>(maxlen*n          );
 		else
 			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
+	}
 
 /*  loop through string to get all values  */
@@ -655,5 +664,5 @@
 /*  get additional token and compare to closing tag  */
 
-	if (ktag)
+	if(ktag){
 		if (!(kstr=KMLFileToken(fid,
 								NULL,NULL)) ||
@@ -664,4 +673,5 @@
 		else
 			xDelete<char>(kstr);
+	}
 
 //	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
@@ -673,6 +683,5 @@
 /*}}}*/
 /*FUNCTION  KMLFileTagSkip {{{*/
-int KMLFileTagSkip(char* ktag,
-				   FILE* fid){
+int KMLFileTagSkip(char* ktag, FILE* fid){
 
 	char*   kstr;
@@ -685,9 +694,6 @@
 /*  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)))) {
+	while((kstr=KMLFileToken(fid,NULL,NULL))){
+		if((kstr[0] == '<') && (kstr[1] == '/') && (!strncmp(&(kstr[2]),&(ktag[1]),(strcspn(ktag," >")-1)/sizeof(char)))){
 			_printf0_("KMLFileTagSkip -- closing tag " << kstr << ".\n");
 			xDelete<char>(kstr);
Index: /issm/trunk/src/c/kml/KML_Document.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Document.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Document.cpp	(revision 16560)
@@ -95,6 +95,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))) {
 		if      (!strncmp(kstri,"</Document",10)) {
 			xDelete<char>(kstri);
@@ -114,5 +113,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for (ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_File.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_File.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_File.cpp	(revision 16560)
@@ -96,6 +96,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</kml", 5)) {
 			xDelete<char>(kstri);
@@ -115,6 +114,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
-		xDelete<char>(pcom[ncom-1]);
+	for(; ncom>0; ncom--) xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
 
Index: /issm/trunk/src/c/kml/KML_Folder.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Folder.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Folder.cpp	(revision 16560)
@@ -95,6 +95,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Folder", 8)) {
 			xDelete<char>(kstri);
@@ -114,6 +113,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
-		xDelete<char>(pcom[ncom-1]);
+	for (ncom=ncom; ncom>0; ncom--) xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
 
Index: /issm/trunk/src/c/kml/KML_GroundOverlay.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 16560)
@@ -122,6 +122,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</GroundOverlay",15)) {
 			xDelete<char>(kstri);
@@ -154,5 +153,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Icon.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Icon.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Icon.cpp	(revision 16560)
@@ -134,6 +134,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Icon", 6)) {
 			xDelete<char>(kstri);
@@ -170,5 +169,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_LatLonBox.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 16560)
@@ -109,6 +109,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</LatLonBox",11)) {
 			xDelete<char>(kstri);
@@ -149,5 +148,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for (ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_LineString.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 16560)
@@ -129,6 +129,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</LineString",12)) {
 			xDelete<char>(kstri);
@@ -165,5 +164,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for (ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_LineStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 16560)
@@ -101,6 +101,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</LineStyle",11)) {
 			xDelete<char>(kstri);
@@ -125,5 +124,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_LinearRing.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 16560)
@@ -127,5 +127,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,&ncom,&pcom)){
+	while((kstri=KMLFileToken(fid,&ncom,&pcom))){
 		if (!strncmp(kstri,"</LinearRing",12)){
 			xDelete<char>(kstri);
@@ -153,5 +153,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for(ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_MultiGeometry.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 16560)
@@ -134,6 +134,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</MultiGeometry",15)) {
 			xDelete<char>(kstri);
@@ -183,5 +182,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Object.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Object.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Object.cpp	(revision 16560)
@@ -295,31 +295,4 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::FindAttrib {{{*/
-void  KML_Object::FindAttrib(char** pvalue,char* name,char* deflt){
-
-	int   i;
-	KML_Attribute* katt=NULL;
-
-/*  loop over any attributes for the object  */
-
-	if (attrib->Size())
-		for (i=0; i<attrib->Size(); i++)
-			if (!strcmp(((KML_Attribute *)attrib->GetObjectByOffset(i))->name,name)) {
-				katt=(KML_Attribute *)attrib->GetObjectByOffset(i);
-				break;
-			}
-
-/*  if found, get the value; otherwise use the default  */
-
-	if (katt)
-		katt->Get(pvalue,deflt);
-	else {
-		*pvalue=xNew<char>(strlen(deflt)+1);
-		memcpy(*pvalue,deflt,(strlen(deflt)+1)*sizeof(char));
-	}
-
-	return;
-}
-/*}}}*/
 /*FUNCTION KML_Object::WriteAttrib {{{*/
 void  KML_Object::WriteAttrib(FILE* filout,const char* indent){
@@ -363,22 +336,4 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::FindCommnt {{{*/
-void  KML_Object::FindCommnt(char** pvalue,int inum){
-
-	KML_Comment* kcom=NULL;
-
-/*  loop over any comments for the object  */
-
-	if (inum <= commnt->Size())
-		kcom=(KML_Comment *)commnt->GetObjectByOffset(inum-1);
-
-/*  if found, get the value; otherwise use the NULL  */
-
-	if (kcom)
-		kcom->Get(pvalue);
-
-	return;
-}
-/*}}}*/
 /*FUNCTION KML_Object::WriteCommnt {{{*/
 void  KML_Object::WriteCommnt(FILE* filout,const char* indent){
Index: /issm/trunk/src/c/kml/KML_Object.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Object.h	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Object.h	(revision 16560)
@@ -37,9 +37,7 @@
 		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);
 
Index: /issm/trunk/src/c/kml/KML_Placemark.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 16560)
@@ -135,6 +135,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Placemark",11)) {
 			xDelete<char>(kstri);
@@ -184,5 +183,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Point.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Point.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Point.cpp	(revision 16560)
@@ -114,6 +114,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Point", 7)) {
 			xDelete<char>(kstri);
@@ -140,5 +139,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_PolyStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 16560)
@@ -107,6 +107,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</PolyStyle",11)) {
 			xDelete<char>(kstri);
@@ -135,5 +134,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Polygon.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 16560)
@@ -169,6 +169,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Polygon", 9)) {
 			xDelete<char>(kstri);
@@ -197,6 +196,5 @@
 /*  loop over and process fields within outer boundary  */
 
-			while (kstrj=KMLFileToken(fid,
-									  &ncom,&pcom)) {
+			while((kstrj=KMLFileToken(fid, &ncom,&pcom))){
 				if      (!strncmp(kstrj,"</outerBoundaryIs",17)) {
 					xDelete<char>(kstrj);
@@ -224,6 +222,5 @@
 /*  loop over and process fields within inner boundaries  */
 
-			while (kstrj=KMLFileToken(fid,
-									  &ncom,&pcom)) {
+			while((kstrj=KMLFileToken(fid, &ncom,&pcom))){
 				if      (!strncmp(kstrj,"</innerBoundaryIs",17)) {
 					xDelete<char>(kstrj);
@@ -255,5 +252,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Style.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Style.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Style.cpp	(revision 16560)
@@ -180,6 +180,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 		if      (!strncmp(kstri,"</Style", 7)) {
 			xDelete<char>(kstri);
@@ -229,5 +228,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/kml/KML_Unknown.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 16559)
+++ /issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 16560)
@@ -43,8 +43,10 @@
 	KML_Object::Echo();
 
-	if (value     )
+	if(value){
 		if(flag) _printf0_("         value: \"" << value << "\"\n");
-    else
-        if(flag) _printf0_("         value: [none]\n");
+	}
+	else{
+		if(flag) _printf0_("         value: [none]\n");
+	}
 
 	return;
@@ -79,5 +81,5 @@
 		if(flag) _printf0_(indent << "         value: \"" << vtoken);
 
-		while (vtoken=strtok(NULL,nl))
+		while((vtoken=strtok(NULL,nl)))
 			if(flag) _printf0_("\n" << indent << "                 " << vtoken);
 		if(flag) _printf0_("\"\n");
@@ -110,5 +112,5 @@
 		fprintf(filout,"%s  %s\n",indent,vtoken);
 
-		while (vtoken=strtok(NULL,nl))
+		while((vtoken=strtok(NULL,nl)))
 			fprintf(filout,"%s  %s\n",indent,vtoken);
 
@@ -146,6 +148,5 @@
 /*  loop over and process fields within opening and closing tags  */
 
-	while (kstri=KMLFileToken(fid,
-							  &ncom,&pcom)) {
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
 //		_printf0_("KML_Unknown::Read -- kstri=" << kstri << ".\n");
 		if      (!strncmp(&kstri[0],"</", 2) &&
@@ -183,5 +184,5 @@
 	this->AddCommnt(ncom,pcom);
 
-	for (ncom; ncom>0; ncom--)
+	for(ncom=ncom; ncom>0; ncom--)
 		xDelete<char>(pcom[ncom-1]);
 	xDelete<char*>(pcom);
Index: /issm/trunk/src/c/main/EnvironmentFinalize.cpp
===================================================================
--- /issm/trunk/src/c/main/EnvironmentFinalize.cpp	(revision 16560)
+++ /issm/trunk/src/c/main/EnvironmentFinalize.cpp	(revision 16560)
@@ -0,0 +1,25 @@
+/*!\file:  EnvironmentFinalize.cpp
+ * \brief: finalize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+
+void EnvironmentFinalize(void){
+
+	int my_rank;
+
+	/*Make sure we are all here*/
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD);
+
+	/*Print closing statement*/
+	ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&my_rank);
+	if(!my_rank) printf("closing MPI\n");
+
+	/*Finalize: */
+	ISSM_MPI_Finalize();
+}
Index: /issm/trunk/src/c/main/EnvironmentInit.cpp
===================================================================
--- /issm/trunk/src/c/main/EnvironmentInit.cpp	(revision 16560)
+++ /issm/trunk/src/c/main/EnvironmentInit.cpp	(revision 16560)
@@ -0,0 +1,35 @@
+/*!\file:  EnvironmentInit.cpp
+ * \brief: initialize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include "../toolkits/toolkits.h"
+
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv){
+
+	/*Output*/
+	ISSM_MPI_Comm comm = 0;
+
+	/*Initialize MPI environment: */
+	#if defined(_HAVE_MPI_)
+	ISSM_MPI_Init(&argc,&argv);
+	comm = ISSM_MPI_COMM_WORLD;
+	#else
+	comm = 1; //bogus number for comm, which does not exist anyway.
+	#endif
+
+	/*Print Banner*/
+	int my_rank = 0;
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	if(!my_rank) printf("\n");
+	if(!my_rank) printf("%s version  %s\n",PACKAGE_NAME,PACKAGE_VERSION);
+	if(!my_rank) printf("(website: %s contact: %s)\n",PACKAGE_URL,PACKAGE_BUGREPORT);
+	if(!my_rank) printf("\n");
+
+	/*Return communicator*/
+	return comm;
+}
Index: /issm/trunk/src/c/main/issm.h
===================================================================
--- /issm/trunk/src/c/main/issm.h	(revision 16559)
+++ /issm/trunk/src/c/main/issm.h	(revision 16560)
@@ -16,7 +16,11 @@
 #include "../classes/classes.h"
 #include "../toolkits/toolkits.h"
-#include "../analyses/analyses.h"
+#include "../cores/cores.h"
 #include "../solutionsequences/solutionsequences.h"
 #include "../modules/modules.h"
 
+/*Environment*/
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv);
+void EnvironmentFinalize(void);
+
 #endif //ifndef _ISSM_H_
Index: /issm/trunk/src/c/main/kriging.cpp
===================================================================
--- /issm/trunk/src/c/main/kriging.cpp	(revision 16559)
+++ /issm/trunk/src/c/main/kriging.cpp	(revision 16560)
@@ -14,5 +14,4 @@
 	FILE *output_fid = NULL;
 	FILE *input_fid  = NULL;
-	bool  waitonlock = false;
 
 	/*File names*/
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 16560)
@@ -24,4 +24,5 @@
 
 	bool oldalloc=false;
+	char* toolkittype=NULL;
 
 	/*retrieve parameters: */
@@ -37,4 +38,8 @@
 	numberofdofspernode=femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
 
+	/*if our matrices are coming from issm, we don't do dynamic allocation like Petsc 
+	 * does, and this routine is essentially useless. Force standard alloc in this case: */
+	toolkittype=ToolkitOptions::GetToolkitType();
+
 	if(oldalloc){
 		if(pKff) Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
@@ -47,20 +52,33 @@
 			m=flocalsize; n=flocalsize; /*local  sizes*/
 			M=fsize;      N=fsize;      /*global sizes*/
-			MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,FsetEnum);
-			Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
-			xDelete<int>(d_nnz);
-			xDelete<int>(o_nnz);
+			if(strcmp(toolkittype,"issm")==0){
+				Kff=new Matrix<IssmDouble>(m,n,M,N,NULL,NULL);
+			}
+			else{
+				MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,FsetEnum);
+				Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+				xDelete<int>(d_nnz);
+				xDelete<int>(o_nnz);
+			}
 		}
 		if(pKfs){
 			m=flocalsize; n=slocalsize; /*local  sizes*/
 			M=fsize;      N=ssize;      /*global sizes*/
-			MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,SsetEnum);
-			Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
-			xDelete<int>(d_nnz);
-			xDelete<int>(o_nnz);
+			if(strcmp(toolkittype,"issm")==0){
+				Kfs=new Matrix<IssmDouble>(m,n,M,N,NULL,NULL);
+			}
+			else{
+				MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,SsetEnum);
+				Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+				xDelete<int>(d_nnz);
+				xDelete<int>(o_nnz);
+			}
 		}
 		if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
 		if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
 	}
+	
+	/*Free ressources: */
+	xDelete<char>(toolkittype);
 
 	/*Allocate output pointers*/
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 16560)
@@ -11,4 +11,3 @@
 void MatrixNonzeros(int** pd_nnz,int** po_nnz,FemModel* femmodel,int set1enum,int set2enum);
 
-
 #endif
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 16560)
@@ -19,5 +19,4 @@
 	int     npart;
 	double *qmu_part  = NULL;
-	int     numberofvertices;
 
 	/*output: */
@@ -31,5 +30,4 @@
 
 	/*Some parameters: */
-	numberofvertices=vertices->NumberOfVertices();
 	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
 
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 16560)
@@ -11,8 +11,6 @@
 
 	/*Intermediary*/
-	int i;
-	int      found=0;
-	IssmDouble   numberofelements;
-	Element* element=NULL;
+	IssmDouble numberofelements;
+	Element*   element=NULL;
 
 	/*output: */
@@ -26,5 +24,5 @@
 
 	/*Compute basal stress for each element: */
-	for (i=0;i<elements->Size();i++){
+	for(int i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->ComputeBasalStress(sigma);
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 16560)
@@ -8,9 +8,7 @@
 #include "../../toolkits/toolkits.h"
 
-void	ComputeStrainRatex( Vector<IssmDouble>** peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
+void	ComputeStrainRatex(Vector<IssmDouble>** peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
-	int i;
-	int      found=0;
 	int      numberofelements;
 	Element* element=NULL;
@@ -26,5 +24,5 @@
 
 	/*Compute basal stress for each element: */
-	for (i=0;i<elements->Size();i++){
+	for(int i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->ComputeStrainRate(eps);
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 16560)
@@ -12,11 +12,10 @@
 
 	/*Intermediary*/
-	int i;
-	int noerr=1;
-	int configuration_type;
-	Element  *element  = NULL;
-	Load     *load     = NULL;
-	Node     *node     = NULL;
-	Material *material = NULL;
+	int       i;
+	int       noerr = 1;
+	int       configuration_type;
+	Element  *element            = NULL;
+	Load     *load               = NULL;
+	Material *material           = NULL;
 
 	/*Get analysis type: */
@@ -24,10 +23,10 @@
 
 	if(VerboseMProcessor()) _printf0_("      Configuring elements...\n");
-	for (i=0;i<elements->Size();i++){
+	for(i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->Configure(elements,loads,nodes,vertices,materials,parameters);
 	}
 	if(VerboseMProcessor()) _printf0_("      Configuring loads...\n");
-	for (i=0;i<loads->Size();i++){
+	for(i=0;i<loads->Size();i++){
 		load=(Load*)loads->GetObjectByOffset(i);
 		if (load->InAnalysis(configuration_type)){
@@ -36,5 +35,5 @@
 	}
 	if(VerboseMProcessor()) _printf0_("      Configuring materials...\n");
-	for (i=0;i<materials->Size();i++){
+	for(i=0;i<materials->Size();i++){
 		material=(Material*)materials->GetObjectByOffset(i);
 		material->Configure(elements);
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 16560)
@@ -6,22 +6,18 @@
 #define _CONSTRAINTSSTATELOCAL_H
 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
 #include "../../classes/classes.h"
 
-/*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);
+void RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int analysis_type);
+void RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int analysis_type);
+int  RiftIsFrozen(Loads* loads,int analysis_type);
+void RiftFreezeConstraints(Loads* loads,int analysis_type);
 
 #endif  /* _CONSTRAINTSSTATEX_H */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 16560)
@@ -11,7 +11,9 @@
 
 	/*output: */
-	int converged                  = 0;
-	int num_unstable_constraints   = 0;
-	int min_mechanical_constraints = 0;
+	int converged                     = 1;
+	int num_unstable_constraints      = 0;
+	int min_mechanical_constraints    = 0;
+	int  unstable                     = 0;
+	int  sum_num_unstable_constraints = 0;
 	int analysis_type;
 
@@ -23,11 +25,5 @@
 	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
-	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
-	 * management routine, otherwise, skip : */
-
-	/*No constraints management by default!:*/
-	num_unstable_constraints=0;
-	converged=1;
-
+	/*Rift penalties first*/
 	#ifdef _HAVE_RIFTS_
 	if(RiftIsPresent(femmodel->loads,analysis_type)){
@@ -35,12 +31,25 @@
 	}
 	#endif
-	#ifdef _HAVE_THERMAL_
-	if(ThermalIsPresent(femmodel->loads,analysis_type)){
-		ThermalConstraintsState(femmodel->loads,&converged,&num_unstable_constraints,analysis_type);
+
+	/*Deal with pengrid*/
+	for(int i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(analysis_type)){
+			if(load->ObjectEnum()==PengridEnum){
+				Pengrid* pengrid=(Pengrid*)load;
+				pengrid->ConstraintActivate(&unstable);
+				num_unstable_constraints += unstable;
+			}
+		}
 	}
-	#endif
+	ISSM_MPI_Reduce(&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	num_unstable_constraints=sum_num_unstable_constraints;
+
+	/*Have we converged? : */
+	if(num_unstable_constraints) converged=0;
 
 	/*Assign output pointers: */
-	*pconverged=converged;
-	*pnum_unstable_constraints=num_unstable_constraints;
+	*pconverged                = converged;
+	*pnum_unstable_constraints = num_unstable_constraints;
 }
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 16560)
@@ -9,5 +9,4 @@
 
 /* local prototypes: */
-int  ThermalIsPresent(Loads* loads,int analysis_type);
 int  RiftIsPresent(Loads* loads,int analysis_type);
 void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints,FemModel* femmodel);
Index: /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 16560)
@@ -159,197 +159,2 @@
 }
 /*}}}*/
-
-/*diverse trials and errors: */
-/*RiftIsMaterialStable(Loads* loads){{{*/
-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!*/
-			}
-		}
-	}
-
-	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	found=mpi_found;
-
-	return found;
-}
-/*}}}*/
-/*RiftIsPreStable(Loads* loads){{{*/
-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;
-			}
-		}
-	}
-
-	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	found=mpi_found;
-
-	if (found){
-		/*We found an unstable constraint. : */
-		return 0;
-	}
-	else{
-		return 1;
-	}
-}
-/*}}}*/
-/*RiftSetPreStable(Loads* loads){{{*/
-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){{{*/
-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;
-		}
-	}
-
-	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	num_unstable_constraints=sum_num_unstable_constraints;
-
-	/*Assign output pointers: */
-	*pnum_unstable_constraints=num_unstable_constraints;
-
-}
-/*}}}*/
-/*RiftMaxPenetrationInInputs(Loads* loads){{{*/
-void RiftMaxPenetrationInInputs(Loads* loads){
-
-	int			i;
-
-	/* generic object pointer: */
-	Riftfront* riftfront=NULL;
-
-	/*rift penetration: */
-	IssmDouble max_penetration=0;
-	IssmDouble mpi_max_penetration;
-	IssmDouble penetration;
-
-	/*Ok, we are going to find the node pairs which are not penetrating, even though they 
-	 * 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;
-		}
-	}
-
-	ISSM_MPI_Reduce (&max_penetration,&mpi_max_penetration,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&mpi_max_penetration,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());                
-	max_penetration=mpi_max_penetration;
-
-	/*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){{{*/
-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;
-		}
-	}
-
-	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	num_unstable_constraints=sum_num_unstable_constraints;
-
-	return num_unstable_constraints;
-}
-/*}}}*/
Index: sm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 16559)
+++ 	(revision )
@@ -1,49 +1,0 @@
-/*!\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;
-			}
-		}
-	}
-
-	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	num_unstable_constraints=sum_num_unstable_constraints;
-
-	/*Have we converged? : */
-	if (num_unstable_constraints==0) converged=1;
-	else converged=0;
-
-	/*Assign output pointers: */
-	*pconverged=converged;
-	*pnum_unstable_constraints=num_unstable_constraints;
-}
Index: sm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 16559)
+++ 	(revision )
@@ -1,35 +1,0 @@
-/*!\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;
-			}
-		}
-	}
-
-	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	found=mpi_found;
-
-	return found;
-}
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 16560)
@@ -13,12 +13,5 @@
 
 	/*Contour:*/
-	double   value;
-
-	/*threading: */
-	ContourToMeshxThreadStruct gate;
-	int num=1;
-	#ifdef _MULTITHREADING_
-	num=_NUMTHREADS_;
-	#endif
+	double value;
 
 	/*output: */
@@ -29,13 +22,14 @@
 
 	/*initialize thread parameters: */
-	gate.contours=contours;
-	gate.nods=nods;
-	gate.edgevalue=edgevalue;
-	gate.in_nod=in_nod;
-	gate.x=x;
-	gate.y=y;
+	ContourToMeshxThreadStruct gate;
+	gate.contours  = contours;
+	gate.nods      = nods;
+	gate.edgevalue = edgevalue;
+	gate.in_nod    = in_nod;
+	gate.x         = x;
+	gate.y         = y;
 
 	/*launch the thread manager with ContourToMeshxt as a core: */
-	LaunchThread(ContourToMeshxt,(void*)&gate,num);
+	LaunchThread(ContourToMeshxt,(void*)&gate,_NUMTHREADS_);
 
 	/*Take care of the case where an element interpolation has been requested: */
@@ -43,5 +37,5 @@
 		for(int n=0;n<nel;n++){
 			if ( (in_nod[ (int)*(index+3*n+0) -1] == 1) && (in_nod[ (int)*(index+3*n+1) -1] == 1) && (in_nod[ (int)*(index+3*n+2) -1] == 1) ){
-				value=1; in_elem[n]=value;
+				value=1.; in_elem[n]=value;
 			}
 		}
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 16560)
@@ -13,39 +13,22 @@
 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:*/
-	Contours* contours=NULL;
-
-	/*parameters: */
-	int nods;
-	int edgevalue;
-	double* x=NULL;
-	double* y=NULL;
-	double* in_nod=NULL;
+	ContourToMeshxThreadStruct *gate        = NULL;
+	pthread_handle             *handle      = NULL;
+	int  i,i1,i0;
 
 	/*recover handle and gate: */
-	handle=(pthread_handle*)vpthread_handle;
-	gate=(ContourToMeshxThreadStruct*)handle->gate;
-	my_thread=handle->id;
-	num_threads=handle->num;
+	handle          = (pthread_handle*)vpthread_handle;
+	gate            = (ContourToMeshxThreadStruct*)handle->gate;
+	int my_thread   = handle->id;
+	int num_threads = handle->num;
 
 	/*recover parameters :*/
-	contours=gate->contours;
-	nods=gate->nods;
-	edgevalue=gate->edgevalue;
-	in_nod=gate->in_nod;
-	x=gate->x;
-	y=gate->y;
+	Contours* contours  = gate->contours;
+	int       nods      = gate->nods;
+	int       edgevalue = gate->edgevalue;
+	double   *in_nod    = gate->in_nod;
+	double   *x         = gate->x;
+	double   *y         = gate->y;
 
 	/*distribute indices across threads :*/
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 16560)
@@ -34,9 +34,4 @@
 int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contours* contours, int edgevalue){
 
-	/*Contour:*/
-	Contour<IssmPDouble>* contouri=NULL;
-	double*  xc=NULL;
-	double*  yc=NULL;
-
 	/*output: */
 	IssmPDouble* flags=NULL;
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 16560)
@@ -11,6 +11,5 @@
 
 	int      i,connectivity;
-	int      numberofdofspernode;
-	int      fsize,configuration_type;
+	int      configuration_type;
 	Element *element = NULL;
 	Load    *load    = NULL;
@@ -23,6 +22,4 @@
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	femmodel->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
-	fsize=femmodel->nodes->NumberOfDofs(configuration_type,FsetEnum);
-	numberofdofspernode=femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
 
 	/*Initialize Jacobian Matrix*/
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->DragCoefficientAbsGradient(weight_index);
+		J+=element->DragCoefficientAbsGradient();
 	}
 
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 16560)
@@ -86,5 +86,5 @@
 	sprintf(klsty->color     ,"ff000000");
 	sprintf(klsty->colormode ,"normal");
-	klsty->width     ,lwidth;
+	klsty->width     =lwidth;
 	kpsty =new KML_PolyStyle();
 	sprintf(kpsty->color     ,"00ffffff");
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 16560)
@@ -92,20 +92,20 @@
 
 	/*Recover material parameters and loading history: see GiaDeflectionCoreArgs for more details {{{*/
-	ri=arguments->ri;
-	re=arguments->re;
-	hes=arguments->hes;
-	times=arguments->times;
-	numtimes=arguments->numtimes;
-	currenttime=arguments->currenttime;
-	lithosphere_shear_modulus=arguments->lithosphere_shear_modulus;
-	lithosphere_density=arguments->lithosphere_density;
-	mantle_shear_modulus=arguments->mantle_shear_modulus;
-	mantle_viscosity=arguments->mantle_viscosity;
-	mantle_density=arguments->mantle_density;
-	lithosphere_thickness=arguments->lithosphere_thickness;
-	rho_ice=arguments->rho_ice; 
-	disk_id=arguments->idisk;
-	iedge=arguments->iedge;
-	yts=arguments->yts;
+	ri                        = arguments->ri;
+	re                        = arguments->re;
+	hes                       = arguments->hes;
+	times                     = arguments->times;
+	numtimes                  = arguments->numtimes;
+	currenttime               = arguments->currenttime;
+	lithosphere_shear_modulus = arguments->lithosphere_shear_modulus;
+	lithosphere_density       = arguments->lithosphere_density;
+	mantle_shear_modulus      = arguments->mantle_shear_modulus;
+	mantle_viscosity          = arguments->mantle_viscosity;
+	mantle_density            = arguments->mantle_density;
+	lithosphere_thickness     = arguments->lithosphere_thickness;
+	rho_ice                   = arguments->rho_ice;
+	disk_id                   = arguments->idisk;
+	iedge                     = arguments->iedge;
+	yts                       = arguments->yts;
 
 	/*}}}*/
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 16560)
@@ -34,4 +34,5 @@
 
 		for(j=0;j<elements->Size();j++){
+
 			Element* element=(Element*)elements->GetObjectByOffset(j);
 			element->Gradj(gradient_list[i],control_type[i],i);
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 16560)
@@ -30,5 +30,5 @@
 
 	/*Set toolkit to default*/
-	ToolkitsOptionsFromAnalysis(parameters,NoneAnalysisEnum);
+	ToolkitsOptionsFromAnalysis(parameters,DefaultAnalysisEnum);
 
 	if(migration_style==SoftMigrationEnum){
@@ -80,5 +80,5 @@
 /*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
 IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ 
-	int                 i,analysis_type,numberofvertices;
+	int                 i,analysis_type;
 	int                 nflipped,local_nflipped;
 	IssmDouble*         phi                                  = NULL;
@@ -86,10 +86,8 @@
 	Vector<IssmDouble>* vec_elements_neighboring_floatingice = NULL;
 	Vector<IssmDouble>* vec_phi                              = NULL;
-	Node*               node                                  = NULL;
 	Element*            element                               = NULL;
 
 	/*recover parameters: */
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	numberofvertices=vertices->NumberOfVertices();
 
 	/*recover vec_phi*/
Index: /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp
===================================================================
--- /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 16560)
@@ -342,6 +342,4 @@
 	#endif
 
-	end:
-
 	/*Assign output pointers: */
 	*pimageout=imageout;
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 16560)
@@ -8,14 +8,13 @@
 #include "../../toolkits/toolkits.h"
 
-void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int original_enum, int new_enum){
+void InputDuplicatex(FemModel* femmodel,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=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputDuplicate(original_enum,new_enum);
 	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(int i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputDuplicate(original_enum,new_enum);
 	}
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 16559)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int reinitialized_enum, int original_enum);
+void InputDuplicatex(FemModel* femmodel,int reinitialized_enum, int original_enum);
 
 #endif  /* _INPUTDUPLICATEX_H */
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 16560)
@@ -71,2 +71,13 @@
 
 }
+void InputUpdateFromConstantx(Elements* elements,IssmDouble constant, int name){
+
+	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->InputUpdateFromConstant(constant,name);
+	}
+}
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 16560)
@@ -9,7 +9,8 @@
 
 /* local prototypes: */
-void InputUpdateFromConstantx(FemModel* femmode,bool   constant    ,int name);
-void InputUpdateFromConstantx(FemModel* femmode,int    constant    ,int name);
-void InputUpdateFromConstantx(FemModel* femmode,IssmDouble constant,int name);
+void InputUpdateFromConstantx(FemModel* femmodel,bool       constant,int name);
+void InputUpdateFromConstantx(FemModel* femmodel,int        constant,int name);
+void InputUpdateFromConstantx(FemModel* femmodel,IssmDouble constant,int name);
+void InputUpdateFromConstantx(Elements* elements,IssmDouble constant,int name);
 
 #endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 16560)
@@ -26,11 +26,4 @@
 	int     i;
 
-	/*threading: */
-	InterpFromGridToMeshxThreadStruct gate;
-	int num=1;
-	#ifdef _MULTITHREADING_
-	num=_NUMTHREADS_;
-	#endif
-
 	/*Some checks on arguments: */
 	if ((M<2) || (N<2) || (nods<=0)){
@@ -53,6 +46,6 @@
 		x=xNew<double>(N);
 		y=xNew<double>(M);
-		for (i=0;i<N;i++) x[i]=(x_in[i]+x_in[i+1])/2;
-		for (i=0;i<M;i++) y[i]=(y_in[i]+y_in[i+1])/2;
+		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;
@@ -63,6 +56,6 @@
 		x=xNew<double>(N);
 		y=xNew<double>(M);
-		for (i=0;i<N;i++) x[i]=x_in[i];
-		for (i=0;i<M;i++) y[i]=y_in[i];
+		for(i=0;i<N;i++) x[i]=x_in[i];
+		for(i=0;i<M;i++) y[i]=y_in[i];
 	}
 	else{
@@ -71,20 +64,21 @@
 
 	/*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.default_value=default_value;
-	gate.interp=interpenum;
-	gate.M=M;
-	gate.N=N;
+	InterpFromGridToMeshxThreadStruct gate;
+	gate.x_mesh        = x_mesh;
+	gate.y_mesh        = y_mesh;
+	gate.x_rows        = x_rows;
+	gate.y_rows        = y_rows;
+	gate.x             = x;
+	gate.y             = y;
+	gate.nods          = nods;
+	gate.data_mesh     = data_mesh;
+	gate.data          = data;
+	gate.default_value = default_value;
+	gate.interp        = interpenum;
+	gate.M             = M;
+	gate.N             = N;
 
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
-	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,num);
+	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,_NUMTHREADS_);
 	_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
@@ -134,5 +128,4 @@
 
 	bool debug = M*N>1? true:false;
-	debug = true;
 
 	/*partition loop across threads: */
@@ -188,4 +181,6 @@
 		data_mesh->SetValue(i,data_value,INS_VAL);
 	}
+
+	return NULL;
 }/*}}}*/
 
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 16560)
@@ -25,13 +25,5 @@
 
 	/*contours: */
-	double              *incontour     = NULL;
-
-	/*threading: */
-	InterpFromMesh2dxThreadStruct gate;
-	int num=1;
-
-	#ifdef _MULTITHREADING_
-	num=_NUMTHREADS_;
-	#endif
+	double *incontour     = NULL;
 
 	/*some checks*/
@@ -84,25 +76,26 @@
 
 	/*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;
+	InterpFromMesh2dxThreadStruct gate;
+	gate.interpolation_type = interpolation_type;
+	gate.debug              = debug;
+	gate.nels_data          = nels_data;
+	gate.index_data         = index_data;
+	gate.x_data             = x_data;
+	gate.y_data             = y_data;
+	gate.data               = data;
+	gate.xmin               = xmin;
+	gate.xmax               = xmax;
+	gate.ymin               = ymin;
+	gate.ymax               = ymax;
+	gate.nods_prime         = nods_prime;
+	gate.data_prime         = data_prime;
+	gate.x_prime            = x_prime;
+	gate.y_prime            = y_prime;
+	gate.default_values     = default_values;
+	gate.num_default_values = num_default_values;
+	gate.incontour          = incontour;
 
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
-	LaunchThread(InterpFromMesh2dxt,(void*)&gate,num);
+	LaunchThread(InterpFromMesh2dxt,(void*)&gate,_NUMTHREADS_);
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 16560)
@@ -99,5 +99,5 @@
 
 			/*Inside convex but outside mesh*/
-			if (reft[it]<0 & isdefault){
+			if (reft[it]<0 && isdefault){
 				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
 				continue;
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 16560)
@@ -11,5 +11,4 @@
 
 	/*intermediary: */
-	FILE       *fid = NULL;
 	int         code,vector_layout;
 	IssmDouble *spcdata = NULL;
@@ -17,5 +16,5 @@
 
 	/*First of, find the record for the enum, and get code  of data type: */
-	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
+	iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
 	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
 	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
@@ -49,8 +48,9 @@
 			break;
 		case P1bubbleEnum:
-			switch(iomodel->dim){
-				case 2: elementnbv = 3; break;
-				case 3: elementnbv = 6; break;
-				default: _error_("3d is the only supported dimension");
+			switch(iomodel->meshtype){
+				case Mesh2DhorizontalEnum: elementnbv = 3; break;
+				case Mesh2DverticalEnum:   elementnbv = 3; break;
+				case Mesh3DEnum:           elementnbv = 6; break;
+				default: _error_("mesh type not supported yet");
 			}
 			break;
Index: /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 16560)
@@ -22,6 +22,5 @@
 /*  read kml file  */
 
-	while (kstr=KMLFileToken(fid,
-							 NULL,NULL)) {
+	while((kstr=KMLFileToken(fid, NULL,NULL))){
 		if      (!strncmp(kstr,"<?xml"    ,5)) {
 			kxml=new KML_File();
Index: /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 16560)
@@ -56,5 +56,5 @@
 	sprintf(klsty->color     ,"ff000000");
 	sprintf(klsty->colormode ,"normal");
-	klsty->width     ,lwidth;
+	klsty->width     =lwidth;
 	kpsty=new KML_PolyStyle();
 	sprintf(kpsty->color     ,"00ffffff");
Index: /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 16560)
@@ -8,28 +8,20 @@
 #include "../KMLFileReadx/KMLFileReadx.h"
 
-int Kml2Expx(char* filkml,char* filexp,
-			 int sgn){
+int Kml2Expx(char* filkml,char* filexp,int sgn){
 
 	double  cm,sp;
-
 	Ll2xydef(&cm,&sp,sgn);
 
-	return(Kml2Expx(filkml,filexp,
-					sgn,cm,sp));
+	return(Kml2Expx(filkml,filexp,sgn,cm,sp));
 }
 
-int Kml2Expx(char* filkml,char* filexp,
-			 int sgn,double cm,double sp){
+int Kml2Expx(char* filkml,char* filexp,int sgn,double cm,double sp){
 
-	int     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;
+	int         iret   = 0;
+	KML_Object *kobj   = NULL;
+	FILE       *fidi   = NULL;
+	FILE       *fido   = NULL;
+	clock_t     clock0,clock1;
+	time_t      time0 ,time1;
 
 	clock0=clock();
@@ -37,24 +29,19 @@
 	_printf0_("\nKml2Expx Module -- " << ctime(&time0));
 
-/*  read kml file  */
-
+	/*read kml file*/
 	fidi=fopen(filkml,"r");
 	if (!(kobj=KMLFileReadx(fidi)))
-		_error_("Error reading kml file.");
+	 _error_("Error reading kml file.");
 	fclose(fidi);
 
-/*  open exp file  */
-
+	/*open exp file*/
 	_printf0_("Writing exp profiles to file.\n");
 	fido=fopen(filexp,"w");
 
-/*  write the polygons and linestrings  */
-
+	/*write the polygons and linestrings  */
 	kobj->WriteExp(fido,"",sgn,cm,sp);
 
-/*  close exp file  */
-
+	/*close exp file  */
 	fclose(fido);
-
 	delete kobj;
 
Index: /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 16560)
@@ -28,8 +28,5 @@
 	/*threading: */
 	KrigingxThreadStruct gate;
-	int num=1;
-#ifdef _MULTITHREADING_
-	num=_NUMTHREADS_;
-#endif
+	int num = _NUMTHREADS_;
 
 	/*Get Variogram from Options*/
Index: /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 16560)
@@ -11,5 +11,5 @@
 template <class doubletype> 
 int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,int* elements,
-		int numberofelements2d,int numberofnodes2d,doubletype* elements2d,int numlayers,int elements_width, int dim,int num_procs){
+		int numberofelements2d,int numberofnodes2d,doubletype* elements2d,int numlayers,int elements_width, int meshtype,int num_procs){
 
 	int noerr=1;
@@ -31,79 +31,108 @@
 	int  edgecut=1;
 
-	if(dim==2){
-		epart=xNew<int>(numberofelements);
-		npart=xNew<int>(numberofnodes);
-		index=xNew<int>(elements_width*numberofelements);
-		for (i=0;i<numberofelements;i++){
-			for (j=0;j<elements_width;j++){
-				*(index+elements_width*i+j)=(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+	switch(meshtype){
+		case Mesh2DhorizontalEnum:
+			epart=xNew<int>(numberofelements);
+			npart=xNew<int>(numberofnodes);
+			index=xNew<int>(elements_width*numberofelements);
+			for (i=0;i<numberofelements;i++){
+				for (j=0;j<elements_width;j++){
+					*(index+elements_width*i+j)=(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+				}
 			}
-		}
 
-		/*Partition using Metis:*/
-		if (num_procs>1){
-			#ifdef _HAVE_METIS_
-			METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
-			#else
-			_error_("metis has not beed installed. Cannot run with more than 1 cpu");
-			#endif
-		}
-		else if (num_procs==1){
-			/*METIS does not know how to deal with one cpu only!*/
-			for (i=0;i<numberofelements;i++) epart[i]=0;
-			for (i=0;i<numberofnodes;i++)    npart[i]=0;
-		}
-		else _error_("At least one processor is required");
-	}
-	else{
-		/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
+			/*Partition using Metis:*/
+			if (num_procs>1){
+#ifdef _HAVE_METIS_
+				METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
+#else
+				_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+#endif
+			}
+			else if (num_procs==1){
+				/*METIS does not know how to deal with one cpu only!*/
+				for (i=0;i<numberofelements;i++) epart[i]=0;
+				for (i=0;i<numberofnodes;i++)    npart[i]=0;
+			}
+			else _error_("At least one processor is required");
+			break;
+		case Mesh2DverticalEnum:
+			epart=xNew<int>(numberofelements);
+			npart=xNew<int>(numberofnodes);
+			index=xNew<int>(elements_width*numberofelements);
+			for (i=0;i<numberofelements;i++){
+				for (j=0;j<elements_width;j++){
+					*(index+elements_width*i+j)=(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+				}
+			}
 
-		/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
-		epart2d=xNew<int>(numberofelements2d);
-		npart2d=xNew<int>(numberofnodes2d); 
-		index2d=xNew<int>(3*numberofelements2d);
+			/*Partition using Metis:*/
+			if (num_procs>1){
+#ifdef _HAVE_METIS_
+				METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
+#else
+				_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+#endif
+			}
+			else if (num_procs==1){
+				/*METIS does not know how to deal with one cpu only!*/
+				for (i=0;i<numberofelements;i++) epart[i]=0;
+				for (i=0;i<numberofnodes;i++)    npart[i]=0;
+			}
+			else _error_("At least one processor is required");
+			break;
+		case Mesh3DEnum:
+			/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
 
-		for (i=0;i<numberofelements2d;i++){
-			for (j=0;j<3;j++){
-				*(index2d+3*i+j)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
+			/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
+			epart2d=xNew<int>(numberofelements2d);
+			npart2d=xNew<int>(numberofnodes2d); 
+			index2d=xNew<int>(3*numberofelements2d);
+
+			for (i=0;i<numberofelements2d;i++){
+				for (j=0;j<3;j++){
+					*(index2d+3*i+j)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
+				}
 			}
-		}
 
-		/*Partition using Metis:*/
-		if (num_procs>1){
-			#ifdef _HAVE_METIS_
-			METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
-			#else
-			_error_("metis has not beed installed. Cannot run with more than 1 cpu");
-			#endif
-		}
-		else if (num_procs==1){
-			/*METIS does not know how to deal with one cpu only!*/
-			for (i=0;i<numberofelements2d;i++) epart2d[i]=0;
-			for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
-		}
-		else _error_("At least one processor is required");
+			/*Partition using Metis:*/
+			if (num_procs>1){
+#ifdef _HAVE_METIS_
+				METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
+#else
+				_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+#endif
+			}
+			else if (num_procs==1){
+				/*METIS does not know how to deal with one cpu only!*/
+				for (i=0;i<numberofelements2d;i++) epart2d[i]=0;
+				for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
+			}
+			else _error_("At least one processor is required");
 
-		/*Extrude epart2d to epart, using numlayers: */
-		epart=xNew<int>(numberofelements);
+			/*Extrude epart2d to epart, using numlayers: */
+			epart=xNew<int>(numberofelements);
 
-		count=0;
-		for(i=0;i<(numlayers-1);i++){
-			for(j=0;j<numberofelements2d;j++){
-				epart[count]=epart2d[j];
-				count++;
+			count=0;
+			for(i=0;i<(numlayers-1);i++){
+				for(j=0;j<numberofelements2d;j++){
+					epart[count]=epart2d[j];
+					count++;
+				}
 			}
-		}
 
-		/*Extrude npart2d to npart, using numlayers: */
-		npart=xNew<int>(numberofnodes);
+			/*Extrude npart2d to npart, using numlayers: */
+			npart=xNew<int>(numberofnodes);
 
-		count=0;
-		for(i=0;i<(numlayers);i++){
-			for(j=0;j<numberofnodes2d;j++){
-				npart[count]=npart2d[j];
-				count++;
+			count=0;
+			for(i=0;i<(numlayers);i++){
+				for(j=0;j<numberofnodes2d;j++){
+					npart[count]=npart2d[j];
+					count++;
+				}
 			}
-		}
+			break;
+		default:
+			_error_("mesh type "<<EnumToStringx(meshtype)<<" not supported yet");
 	}
 
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 16560)
@@ -75,6 +75,5 @@
 
 	/*output: */
-	double*  segments=NULL;
-	Segment<double>* segment=NULL;
+	double* segments=NULL;
 	int     numsegs;
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 16560)
@@ -8,12 +8,11 @@
 #include "../ModelProcessorx.h"
 
-void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+void CreateParametersAutodiff(Parameters* parameters,IoModel* iomodel){
 
 	int         i;
-	Parameters *parameters       = NULL;
 	bool        autodiff_analysis;
 	int         num_dependent_objects;
 	int         num_dep=0;
-	int*        names=NULL;
+	char**      names=NULL;
 	int*        types=NULL;
 	int         dummy;
@@ -21,4 +20,5 @@
 	int*        indices=NULL;
 	int         num_indices;
+	char* options=NULL;
 
 	IssmDouble* xp=NULL;
@@ -26,7 +26,4 @@
 	int         num_ind,local_num_ind;
 	DataSet*    dependent_objects=NULL;
-
-	/*Get parameters: */
-	parameters=*pparameters;
 
 	/*retrieve some parameters: */
@@ -37,7 +34,13 @@
 		#ifdef _HAVE_ADOLC_
 
-		/*Copy some parameters from IoModel to parameters dataset: */
+		/*Copy some parameters from IoModel to parameters dataset: {{{*/
 		parameters->AddObject(iomodel->CopyConstantObject(AutodiffKeepEnum));
-
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffObufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffCbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffLbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffTbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffGcTriggerRatioEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffGcTriggerMaxSizeEnum));
+		/*}}}*/
 		/*retrieve driver: {{{*/
 		iomodel->Constant(&autodiff_driver,AutodiffDriverEnum);
@@ -56,4 +59,5 @@
 			xDelete<int>(indices);
 		}
+		xDelete<char>(autodiff_driver);
 		/*}}}*/
 		/*Deal with dependents first: {{{*/
@@ -63,5 +67,5 @@
 
 		if(num_dependent_objects){
-			iomodel->FetchData(&names,&dummy,&dummy,AutodiffDependentObjectNamesEnum);
+			iomodel->FetchData(&names,&dummy,AutodiffDependentObjectNamesEnum);
 			iomodel->FetchData(&types,&dummy,&dummy,AutodiffDependentObjectTypesEnum);
 			iomodel->FetchData(&indices,&dummy,&dummy,AutodiffDependentObjectIndicesEnum);
@@ -74,6 +78,10 @@
 
 			/*Free ressources:*/
-			xDelete<int>(names);
+			for(i=0;i<num_dependent_objects;i++){
+				char* string=names[i]; xDelete<char>(string);
+			}
+			xDelete<char*>(names);
 			xDelete<int>(types);
+			xDelete<int>(indices);
 		}
 		parameters->AddObject(new DataSetParam(AutodiffDependentObjectsEnum,dependent_objects));
@@ -100,4 +108,5 @@
 			}
 			xp=xp_backup; parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_ind));
+			xDelete<IssmDouble>(xp);
 		}
 		parameters->AddObject(new IntParam(AutodiffNumIndependentsEnum,num_ind));
@@ -113,10 +122,28 @@
 		/*initialize a placeholder to store solver pointers: {{{*/
 		GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
-		#ifdef _HAVE_GSL_
-		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
-		#endif
-		#ifdef _HAVE_MUMPS_
-		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(mumpsSolveEDF);
-		#endif
+
+		/*Solver pointers depend on what type of solver we are implementing: */
+		options=OptionsFromAnalysis(parameters,DefaultAnalysisEnum); //options database is not filled in yet, use default.
+		ToolkitOptions::Init(options);
+
+		switch(IssmSolverTypeFromToolkitOptions()){
+			case MumpsEnum:{
+				#ifdef _HAVE_MUMPS_
+				theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(mumpsSolveEDF);
+				#else
+				_error_("requesting mumps solver without MUMPS being compiled in!");
+				#endif
+				break;
+							}
+			case GslEnum: {
+				#ifdef _HAVE_GSL_
+				theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
+				#endif
+			    break;
+						  }
+			default:
+				_error_("solver type not supported yet!");
+		}
+
 		// to save some space:
 		// we know we won't use adolc inside of  the solver:
@@ -127,9 +154,9 @@
 		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_x_changes=false;
 		parameters->AddObject(theAdolcEDF_p);
+
+		/*Free ressources: */
+		xDelete<char>(options);
 		/*}}}*/
 	#endif
 
-	/*Assign output pointer: */
-	*pparameters=parameters;
-
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 16560)
@@ -8,7 +8,6 @@
 #include "../ModelProcessorx.h"
 
-void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type){
 
-	Parameters *parameters       = NULL;
 	bool        control_analysis,tao_analysis;
 	int         nsteps;
@@ -16,11 +15,8 @@
 	int         num_cm_responses;
 	int        *control_type     = NULL;
-	IssmDouble *cm_responses     = NULL;
+	int        *cm_responses     = NULL;
 	IssmDouble *cm_jump          = NULL;
 	IssmDouble *optscal          = NULL;
 	IssmDouble *maxiter          = NULL;
-
-	/*Get parameters: */
-	parameters=*pparameters;
 
 	/*retrieve some parameters: */
@@ -37,9 +33,8 @@
 		if(!tao_analysis){
 			parameters->AddObject(iomodel->CopyConstantObject(InversionCostFunctionThresholdEnum));
-			parameters->AddObject(iomodel->CopyConstantObject(InversionGradientOnlyEnum));
 		}
 
 		/*What solution type?*/
-		if (solution_type==SteadystateSolutionEnum){
+		if(solution_type==SteadystateSolutionEnum){
 			parameters->AddObject(new BoolParam(ControlSteadyEnum,true));
 		}
@@ -50,5 +45,5 @@
 		/*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_responses,NULL,&num_cm_responses,InversionCostFunctionsEnum);
 		if(!tao_analysis){
 			iomodel->FetchData(&cm_jump,&nsteps,NULL,InversionStepThresholdEnum);
@@ -59,10 +54,10 @@
 		if(tao_analysis){
 			parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_control_type));
-			parameters->AddObject(new DoubleVecParam(InversionCostFunctionsEnum,cm_responses,num_cm_responses));
+			parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,cm_responses,num_cm_responses));
 		}
 		else{
 			parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_control_type));
+			parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,cm_responses,num_cm_responses));
 			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));
@@ -70,11 +65,8 @@
 
 		xDelete<int>(control_type);
-		iomodel->DeleteData(cm_responses,InversionCostFunctionsEnum);
+		xDelete<int>(cm_responses);
 		iomodel->DeleteData(cm_jump,InversionStepThresholdEnum);
 		iomodel->DeleteData(optscal,InversionGradientScalingEnum);
 		iomodel->DeleteData(maxiter,InversionMaxiterPerStepEnum);
 	}
-
-	/*Assign output pointer: */
-	*pparameters=parameters;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 16560)
@@ -27,9 +27,9 @@
 
 	/*Fetch data needed: */
-	iomodel->FetchDataToInput(elements,InversionVxObsEnum);
-	iomodel->FetchDataToInput(elements,InversionVyObsEnum); 
-	iomodel->FetchDataToInput(elements,InversionThicknessObsEnum);
+	iomodel->FetchDataToInput(elements,InversionVxObsEnum,0.);
+	iomodel->FetchDataToInput(elements,InversionVyObsEnum,0.); 
+	iomodel->FetchDataToInput(elements,InversionThicknessObsEnum,0.);
 
-	iomodel->FetchData(4,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	iomodel->FetchData(5,InversionControlParametersEnum,InversionCostFunctionsEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 	for(i=0;i<num_control_type;i++){
 		switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
@@ -40,5 +40,5 @@
 			case FrictionCoefficientEnum:   iomodel->FetchData(1,FrictionCoefficientEnum); break;
 			case MaterialsRheologyBbarEnum: iomodel->FetchData(1,MaterialsRheologyBEnum); break;
-			case MaterialsRheologyZbarEnum: iomodel->FetchData(1,MaterialsRheologyZEnum); break;
+			case DamageDbarEnum: iomodel->FetchData(1,DamageDEnum); break;
 			default: _error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
 		}
@@ -59,4 +59,4 @@
 
 	/*Free data: */
-	iomodel->DeleteData(4+7,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,ThicknessEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,MaterialsRheologyZEnum);
+	iomodel->DeleteData(5+7,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionCostFunctionsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,ThicknessEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,DamageDEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 16559)
+++ 	(revision )
@@ -1,197 +1,0 @@
-/*!\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 "../../classes/classes.h"
-#include "../../shared/shared.h"
-#include "../MeshPartitionx/MeshPartitionx.h"
-#include "./ModelProcessorx.h"
-
-void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
-
-	Elements   *elements   = NULL;
-	Materials  *materials  = NULL;
-	Parameters *parameters = NULL;
-
-	/*Process Finite Element Mesh*/
-
-	/*Partition Elements and Nodes*/
-	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
-
-	/*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;
-
-	/*Creates Nodes and constraints datasets if empty*/
-	if(!*pnodes)       *pnodes       = new Nodes();
-	if(!*pconstraints) *pconstraints = new Constraints();
-	if(!*ploads)       *ploads       = new Loads();
-
-	/*Now, branch onto analysis dependent model generation: */
-	switch(analysis_type){
-
-		#ifdef _HAVE_STRESSBALANCE_
-		case StressbalanceAnalysisEnum:
-			CreateNodesStressbalance(pnodes,iomodel);
-			CreateConstraintsStressbalance(pconstraints,iomodel);
-			CreateLoadsStressbalance(ploads,iomodel);
-			UpdateElementsStressbalance(elements,iomodel,analysis_counter,analysis_type);
-			break;
-
-		case StressbalanceVerticalAnalysisEnum:
-			CreateNodesStressbalanceVertical(pnodes, iomodel);
-			CreateConstraintsStressbalanceVertical(pconstraints,iomodel);
-			CreateLoadsStressbalanceVertical(ploads,iomodel);
-			UpdateElementsStressbalanceVertical(elements,iomodel,analysis_counter,analysis_type);
-			break;
-
-		case StressbalanceSIAAnalysisEnum:
-			CreateNodesStressbalanceSIA(pnodes, iomodel);
-			CreateConstraintsStressbalanceSIA(pconstraints,iomodel);
-			CreateLoadsStressbalanceSIA(ploads,iomodel);
-			UpdateElementsStressbalanceSIA(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		#endif
-
-		#ifdef _HAVE_HYDROLOGY_
-		case HydrologyShreveAnalysisEnum:
-			CreateNodesHydrologyShreve(pnodes, iomodel);
-			CreateConstraintsHydrologyShreve(pconstraints,iomodel);
-			CreateLoadsHydrologyShreve(ploads,iomodel);
-			UpdateElementsHydrologyShreve(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		case HydrologyDCInefficientAnalysisEnum:
-			CreateNodesHydrologyDCInefficient(pnodes, iomodel);
-			CreateConstraintsHydrologyDCInefficient(pconstraints,iomodel);
-			CreateLoadsHydrologyDCInefficient(ploads,iomodel);
-			UpdateElementsHydrologyDCInefficient(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		case HydrologyDCEfficientAnalysisEnum:
-			CreateNodesHydrologyDCEfficient(pnodes, iomodel);
-			CreateConstraintsHydrologyDCEfficient(pconstraints,iomodel);
-			CreateLoadsHydrologyDCEfficient(ploads,iomodel);
-			UpdateElementsHydrologyDCEfficient(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;
-		case BalancevelocityAnalysisEnum:
-			CreateNodesBalancevelocity(pnodes, iomodel);
-			CreateConstraintsBalancevelocity(pconstraints,iomodel);
-			CreateLoadsBalancevelocity(ploads,iomodel);
-			UpdateElementsBalancevelocity(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		#endif
-
-		#ifdef _HAVE_GIA_
-		case GiaAnalysisEnum:
-			CreateNodesGia(pnodes, iomodel);
-			CreateConstraintsGia(pconstraints,iomodel);
-			CreateLoadsGia(ploads,iomodel);
-			UpdateElementsGia(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_MASSTRANSPORT_
-		case MasstransportAnalysisEnum:
-			CreateNodesMasstransport(pnodes, iomodel);
-			CreateConstraintsMasstransport(pconstraints,iomodel);
-			CreateLoadsMasstransport(ploads,iomodel);
-			UpdateElementsMasstransport(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		case FreeSurfaceTopAnalysisEnum:
-			CreateNodesFreeSurfaceTop(pnodes, iomodel);
-			CreateConstraintsFreeSurfaceTop(pconstraints,iomodel);
-			CreateLoadsFreeSurfaceTop(ploads,iomodel);
-			UpdateElementsFreeSurfaceTop(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		case FreeSurfaceBaseAnalysisEnum:
-			CreateNodesFreeSurfaceBase(pnodes, iomodel);
-			CreateConstraintsFreeSurfaceBase(pconstraints,iomodel);
-			CreateLoadsFreeSurfaceBase(ploads,iomodel);
-			UpdateElementsFreeSurfaceBase(elements,iomodel,analysis_counter,analysis_type);
-			break;
-		#endif
-
-		default:
-			_error_("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,rootpath,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/src/c/modules/ModelProcessorx/CreateEdges.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 16560)
@@ -23,5 +23,5 @@
 
 	/*Mesh dependent variables*/
-	if(iomodel->dim==2){
+	if(iomodel->meshtype==Mesh2DhorizontalEnum){
 		elementnbv = 3;
 		elementnbe = 3;
@@ -32,5 +32,14 @@
 		elementedges[2*2+0] = 0; elementedges[2*2+1] = 1; elementedges_markers[2] = 1;
 	}
-	else if(iomodel->dim==3){
+	else if(iomodel->meshtype==Mesh2DverticalEnum){
+		elementnbv = 3;
+		elementnbe = 3;
+		elementedges         = xNew<int>(elementnbe*2);
+		elementedges_markers = xNew<int>(elementnbe);
+		elementedges[2*0+0] = 1; elementedges[2*0+1] = 2; elementedges_markers[0] = 1;
+		elementedges[2*1+0] = 2; elementedges[2*1+1] = 0; elementedges_markers[1] = 1;
+		elementedges[2*2+0] = 0; elementedges[2*2+1] = 1; elementedges_markers[2] = 1;
+	}
+	else if(iomodel->meshtype==Mesh3DEnum){
 		elementnbv = 6;
 		elementnbe = 9;
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "./ModelProcessorx.h"
 
-void	CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels){
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials,IoModel* iomodel,const int nummodels){
 
 	/*Intermediary*/
@@ -16,9 +16,4 @@
 	bool dakota_analysis;
 
-	/*DataSets: */
-	Elements  *elements  = NULL;
-	Vertices  *vertices  = NULL;
-	Materials *materials = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
@@ -27,26 +22,30 @@
 
 	/*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();
-
-	#ifdef _HAVE_3D_
-	if(iomodel->dim==3)iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
-	#endif
-	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	_assert_(elements->Size()==0);
 
 	/*Create elements*/
-	for(i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-
-			/*Create and add tria element to elements dataset: */
-			if(iomodel->dim==2) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
-	        #ifdef _HAVE_3D_
-			else       elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
-	        #endif
-		}
+	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	switch(iomodel->meshtype){
+		case Mesh2DhorizontalEnum:
+			materials->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		case Mesh2DverticalEnum:
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		#ifdef _HAVE_3D_
+		case Mesh3DEnum:
+			iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		#endif
+		default:
+			_error_("Mesh not supported yet");
 	}
 
@@ -54,16 +53,20 @@
 	switch(materials_type){
 		case MaticeEnum:
-			iomodel->FetchData(2,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
+			iomodel->FetchData(3,MaterialsRheologyBEnum,MaterialsRheologyNEnum,DamageDEnum);
 			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
 			if(dakota_analysis){
-				if(iomodel->dim==2) materials->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum); 
-           #ifdef _HAVE_3D_
-				else       materials->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
-           #endif
+				switch(iomodel->meshtype){
+					case Mesh2DhorizontalEnum:
+						materials->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
+						break;
+				   #ifdef _HAVE_3D_
+					case Mesh3DEnum:
+						materials->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
+						break;
+				   #endif
+					default:
+						_error_("Mesh not supported yet");
+				}
 			}
-			break;
-		case MatdamageiceEnum:
-			iomodel->FetchData(3,MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum);
-			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matdamageice(i+1,i,iomodel));
 			break;
 		default:
@@ -73,5 +76,5 @@
 	/*Free data: */
 	iomodel->DeleteData(8,MeshUpperelementsEnum,MeshLowerelementsEnum,
-				MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum,InversionControlParametersEnum,InversionMinParametersEnum,
+				MaterialsRheologyBEnum,MaterialsRheologyNEnum,DamageDEnum,InversionControlParametersEnum,InversionMinParametersEnum,
 				InversionMaxParametersEnum);
 
@@ -86,19 +89,8 @@
 
 	for(i=0;i<iomodel->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));
-		}
+		if(iomodel->my_vertices[i]) vertices->AddObject(new Vertex(i+1,i,i,iomodel));
 	}
 
 	/*Free data: */
 	iomodel->DeleteData(6,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum,MaskIceLevelsetEnum);
-
-	/*Assign output pointer: */
-	*pelements=elements;
-	*pvertices=vertices;
-	*pmaterials=materials;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 16560)
@@ -12,5 +12,5 @@
 
 	/*Check Iomodel properties*/
-	if(iomodel->dim!=2)             _error_("only 2d model are supported");
+	if(iomodel->meshtype!=Mesh2DhorizontalEnum)             _error_("only 2d model are supported");
 	if(iomodel->numberofvertices<3) _error_("not enough elements in mesh");
 	_assert_(iomodel->elements);
@@ -56,5 +56,5 @@
 
 			/*Go through all processed faces connected to v1 and check whether we have seen this edge yet*/
-			_assert_(v1>=0 & v1<iomodel->numberofvertices);
+			_assert_(v1>=0 && v1<iomodel->numberofvertices);
 			for(int e=head_minv[v1]; e!=-1; e=next_edge[e]){
 				if(facestemp[e*4+1]==v2){
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 16560)
@@ -9,5 +9,5 @@
 #include "./ModelProcessorx.h"
 
-void CreateNodes(Nodes** pnodes, IoModel* iomodel,int analysis,int finite_element,int approximation){
+void CreateNodes(Nodes* nodes, IoModel* iomodel,int analysis,int finite_element,int approximation){
 
 	/*Intermediaries*/
@@ -16,10 +16,4 @@
 	bool *my_nodes = NULL;
 	Node *node     = NULL;
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*First create nodes*/
-	if(!nodes) nodes = new Nodes();
 
 	switch(finite_element){
@@ -228,6 +222,3 @@
 	xDelete<bool>(my_edges);
 	xDelete<bool>(my_nodes);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 16560)
@@ -35,10 +35,10 @@
 	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
 
-	/*Get element width (3 or 6)*/
-	if(iomodel->dim==2){
-		elementswidth=3;
-	}
-	else{
-		elementswidth=6;
+	/*Get element width*/
+	switch(iomodel->meshtype){
+		case Mesh2DhorizontalEnum: elementswidth=3; break;
+		case Mesh2DverticalEnum:   elementswidth=3; break;
+		case Mesh3DEnum:           elementswidth=6; break;
+		default:                   _error_("mesh not supported yet");
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 16560)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 16560)
@@ -0,0 +1,57 @@
+/*!\file: CreateParametersOutputDefinitions.cpp
+ * \brief driver for creating output definitions dataset, and including it into the parameters dataset
+ */ 
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void CreateOutputDefinitions(Parameters* parameters,IoModel* iomodel){
+
+	int i,j;
+	
+	DataSet     *output_definitions      = NULL;
+	int         *output_definition_enums = NULL;
+	int          num_output_definitions;
+	int          numgates;
+	char       **gatenames               = NULL;
+	IssmDouble **gatesegments            = NULL;
+	int         *gatesegments_M          = NULL;
+
+	/*Create output_definitions dataset: */
+	output_definitions=new DataSet();
+	
+	iomodel->FetchData(&output_definition_enums,&num_output_definitions,NULL,OutputdefinitionListEnum);
+	if(num_output_definitions){
+		for (i=0;i<num_output_definitions;i++){
+
+			if (output_definition_enums[i]==MassfluxatgateEnum){
+				/*Deal with mass flux gates:{{{ */
+
+				/*Fetch segments and names: */
+				iomodel->FetchMultipleData(&gatenames,&numgates,MassfluxatgateNameEnum);
+				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&numgates,MassfluxatgateSegmentsEnum);
+
+				for(j=0;j<numgates;j++){
+					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],gatesegments_M[j],gatesegments[j]));
+				}
+				/*Free ressources:*/
+				for(j=0;j<numgates;j++){
+					char*       string = gatenames[j];    xDelete<char>(string);
+					IssmDouble* gate   = gatesegments[j]; xDelete<IssmDouble>(gate);
+				}
+				xDelete<char*>(gatenames);
+				xDelete<IssmDouble*>(gatesegments);
+				xDelete<int>(gatesegments_M);
+				/*}}}*/
+			}
+			else _error_("output definition enum " << output_definition_enums[i] << "not supported yet!");
+		}
+	}
+	parameters->AddObject(new DataSetParam(OutputdefinitionEnum,output_definitions));
+
+	/*Free ressources:*/
+	delete output_definitions;
+	xDelete<int>(output_definition_enums);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 16560)
@@ -13,16 +13,16 @@
 #include "../../shared/shared.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
 #include "./ModelProcessorx.h"
 
-void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter){
+void CreateParameters(Parameters* parameters,IoModel* iomodel,char* rootpath,FILE* toolkitsoptionsfid,const int solution_type){
 
 	int         i,j,m,k;
-	int         numoutputs;
-	Parameters *parameters       = NULL;
-	IssmDouble *requestedoutputs = NULL;
+	int         numoutputs,meshtype;
+	char**      requestedoutputs = NULL;
 	IssmDouble  time;
 	bool        ispdd,isdelta18o;
 
-	/*parameters for mass flux: {{{*/
+	/*parameters for mass flux:*/
 	int          mass_flux_num_profiles     = 0;
 	bool         qmu_mass_flux_present      = false;
@@ -36,26 +36,11 @@
 	IssmDouble  *matrix                     = NULL;
 	int          count;
-	/*}}}*/
-
-	if(*pparameters)return; //do not create parameters twice!
-
-	/*Initialize dataset: */
-	parameters = new Parameters();
+
+	/*Make sure current dataset is empty*/
+	_assert_(parameters->Size()==0); 
 
 	/*Copy some constants from iomodel */
-	parameters->AddObject(iomodel->CopyConstantObject(MeshDimensionEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSIAEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSSAEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsL1L2Enum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsHOEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationFeFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshTypeEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceIsnewtonEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalancePenaltyFactorEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
@@ -82,14 +67,8 @@
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceFSreconditioningEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceShelfDampeningEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceViscosityOvershootEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofverticesEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsIoGatherEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsAsPatchesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsstressbalanceEnum));
@@ -99,4 +78,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgiaEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
@@ -109,4 +89,14 @@
 	parameters->AddObject(iomodel->CopyConstantObject(GiaCrossSectionShapeEnum));
 
+	/*For stress balance only*/
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+	if(iomodel->meshtype==Mesh3DEnum)
+	 parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
+
 	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
 	if(ispdd){
@@ -137,6 +127,4 @@
 	/*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));
 
 	iomodel->Constant(&time,TimesteppingStartTimeEnum);
@@ -147,24 +135,24 @@
 	parameters->AddObject(new BoolParam(SaveResultsEnum,true));
 
-	/*Requested outputs*/
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,StressbalanceRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(StressbalanceNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(StressbalanceRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,StressbalanceRequestedOutputsEnum);
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
+	/*Requested outputs */
+	iomodel->FetchData(&requestedoutputs,&numoutputs,TransientRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,TransientRequestedOutputsEnum);
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,SteadystateRequestedOutputsEnum);
+	if(numoutputs)parameters->AddObject(new StringArrayParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,TransientRequestedOutputsEnum);
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,SteadystateRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,SteadystateRequestedOutputsEnum);
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,MasstransportRequestedOutputsEnum);
+	if(numoutputs)parameters->AddObject(new StringArrayParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,SteadystateRequestedOutputsEnum);
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,MasstransportRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(MasstransportNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,MasstransportRequestedOutputsEnum);
+	if(numoutputs)parameters->AddObject(new StringArrayParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,MasstransportRequestedOutputsEnum);
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
 
 	/*Deal with mass flux segments: {{{*/
@@ -187,4 +175,5 @@
 			temp_m=mdims_array[i];
 			temp_n=ndims_array[i];
+			_assert_(temp_n==5);
 
 			m=0;
@@ -229,25 +218,21 @@
 	/*}}}*/
 
-	/*Solution specific parameters (FIXME: extend to other params)*/
-	#ifdef _HAVE_HYDROLOGY_
-	CreateParametersHydrologyShreve(&parameters,iomodel,solution_type,analysis_type);
-	CreateParametersHydrologyDCInefficient(&parameters,iomodel,solution_type,analysis_type);
-	CreateParametersHydrologyDCEfficient(&parameters,iomodel,solution_type,analysis_type);
-	#endif
+	/*Output definitions dataset: */
+	CreateOutputDefinitions(parameters,iomodel);
 
 	/*Before returning, create parameters in case we are running Qmu or control types runs: */
 	#ifdef _HAVE_CONTROL_
-	CreateParametersControl(&parameters,iomodel,solution_type,analysis_type);
+	CreateParametersControl(parameters,iomodel,solution_type);
 	#endif
 
 	#ifdef _HAVE_DAKOTA_
-	CreateParametersDakota(&parameters,iomodel,rootpath,solution_type,analysis_type);
+	CreateParametersDakota(parameters,iomodel,rootpath);
 	#endif
 
+	/*Now, deal with toolkits options, which need to be put into the parameters dataset: */
+	ParseToolkitsOptionsx(parameters,toolkitsoptionsfid);
+
  	#ifdef _HAVE_ADOLC_
-	CreateParametersAutodiff(&parameters,iomodel,solution_type,analysis_type);
+	CreateParametersAutodiff(parameters,iomodel);
 	#endif
-
-	/*Assign output pointer: */
-	*pparameters=parameters;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 16560)
@@ -30,5 +30,5 @@
 
 	/*Get element width (3 or 6)*/
-	if(iomodel->dim==2){
+	if(iomodel->meshtype==Mesh2DhorizontalEnum){
 		elementswidth=3;
 	}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 16560)
@@ -9,38 +9,29 @@
 #include "../ModelProcessorx.h"
 
-void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type){
+void CreateParametersDakota(Parameters* parameters,IoModel* iomodel,char* rootpath){
 
-	/*variable declarations: {{{*/
-	int i;
-	Parameters* parameters = NULL;
-
-	int*     part=NULL;
-	double*  dpart=NULL;
-
-	char**  responsedescriptors=NULL;
-	int     numresponsedescriptors;
-	char**  variabledescriptors=NULL;
-	int     numvariabledescriptors;
-	char*   descriptor=NULL;
-	double* dakota_parameter=NULL;
+	/*variable declarations*/
+	int          i;
+	int         *part                   = NULL;
+	double      *dpart                  = NULL;
+	char       **responsedescriptors    = NULL;
+	int          numresponsedescriptors;
+	char       **variabledescriptors    = NULL;
+	int          numvariabledescriptors;
+	char        *descriptor             = NULL;
+	double      *dakota_parameter       = NULL;
 
 	//qmu files
-	char* qmuinname=NULL;
-	char* qmuerrname=NULL;
-	char* qmuoutname=NULL;
+	char *qmuinname  = NULL;
+	char *qmuerrname = NULL;
+	char *qmuoutname = NULL;
 
 	//descriptors:
 	char tag[50];
 
-	bool     dakota_analysis=false;
-	char*    name=NULL;
-	int      numberofresponses;
-	int      nrows;
-	int      ncols;
-
-	/*}}}*/
-
-	/*recover parameters : */
-	parameters=*pparameters;
+	bool  dakota_analysis   = false;
+	char *name              = NULL;
+	int   numberofresponses;
+	int   nrows,ncols;
 
 	/*recover parameters: */
@@ -52,5 +43,5 @@
 		iomodel->Constant(&numberofresponses,QmuNumberofresponsesEnum);
 
-		/*name of qmu input, error and output files:{{{*/
+		/*name of qmu input, error and output files*/
 		qmuinname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.in")+1));
 		sprintf(qmuinname,"%s%s%s",rootpath,name,".qmu.in");
@@ -64,6 +55,6 @@
 		sprintf(qmuerrname,"%s%s%s",rootpath,name,".qmu.err");
 		parameters->AddObject(new   StringParam(QmuErrNameEnum,qmuerrname));
-		/*}}}*/
-		/*Fetch variable descriptors: {{{*/
+
+		/*Fetch variable descriptors*/
 		iomodel->FetchData(&variabledescriptors,&numvariabledescriptors,QmuVariabledescriptorsEnum);
 
@@ -71,6 +62,5 @@
 		parameters->AddObject(new StringArrayParam(QmuVariabledescriptorsEnum,variabledescriptors,numvariabledescriptors));
 
-		/*}}}*/
-		/*Fetch response descriptors: {{{*/
+		/*Fetch response descriptors*/
 		iomodel->FetchData(&responsedescriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
 
@@ -78,13 +68,10 @@
 		parameters->AddObject(new StringArrayParam(QmuResponsedescriptorsEnum,responsedescriptors,numresponsedescriptors));
 		parameters->AddObject(new    IntParam(QmuNumberofresponsesEnum,numberofresponses));
-		/*}}}*/
-		/*Deal with partitioning: {{{*/
+
+		/*Deal with partitioning*/
 		/*partition vertices in iomodel->qmu_npart parts, unless a partition is already present: */
-
 		parameters->AddObject(iomodel->CopyConstantObject(QmuNumberofpartitionsEnum));
 		iomodel->FetchData(&dpart,NULL,NULL,QmuPartitionEnum);
-
 		if(!dpart){
-
 			/*Partition elements and vertices and nodes: */
 			ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
@@ -94,9 +81,7 @@
 		}
 		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,iomodel->numberofvertices));
-		/*}}}*/
-		/*Deal with data needed because of qmu variables: {{{*/
 
+		/*Deal with data needed because of qmu variables*/
 		for(i=0;i<numvariabledescriptors;i++){
-
 			if (strncmp(variabledescriptors[i],"scaled_",7)==0){
 				/*Ok, we are dealing with a variable that is distributed over nodes. Recover the name of the variable (ex: scaled_Thickness): */
@@ -105,6 +90,4 @@
 				/*Recover data: */
 				iomodel->FetchData(&dakota_parameter,&nrows,&ncols,StringToEnumx(tag));
-
-				/*Add to parameters: */
 				if(nrows==iomodel->numberofvertices){
 					parameters->AddObject(new DoubleMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
@@ -113,11 +96,9 @@
 					parameters->AddObject(new DoubleTransientMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
 				}
-
-				/*Free ressources:*/
 				xDelete<double>(dakota_parameter);
 			}
 		}
-		/*}}}*/
-		/*Free data: {{{*/
+
+		/*clean-up*/
 		for(i=0;i<numresponsedescriptors;i++){
 			descriptor=responsedescriptors[i];
@@ -125,5 +106,4 @@
 		}
 		xDelete<char*>(responsedescriptors);
-
 		for(i=0;i<numvariabledescriptors;i++){
 			descriptor=variabledescriptors[i];
@@ -136,11 +116,7 @@
 		xDelete<char>(qmuerrname);
 		xDelete<char>(qmuoutname);
-		/*}}}*/
-	} //if(dakota_analysis)
+	}
 
 	/*Free data*/
 	xDelete<char>(name);
-
-	/*Assign output pointer: */
-	*pparameters=parameters;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp	(revision 16560)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp	(revision 16560)
@@ -0,0 +1,20 @@
+/*
+ * UpdateElementsAndMaterialsControl:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel){
+
+	/*recover parameters: */
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	if(dakota_analysis){
+		iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum,0.);
+	}
+}
Index: sm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 16559)
+++ 	(revision )
@@ -1,129 +1,0 @@
-/*!\file:  DistributeNumDofs.cpp
- * \brief: figure out the maximum number of dofs per node.
- */ 
-
-#include "../../shared/shared.h"
-#include "../../classes/classes.h"
-
-void DistributeNumDofs(DofIndexing* index,int analysis_type,int node_type){
-
-	/*For now, we distribute by analysis_type, later, we will distribute using the analysis_type,
-	 * but also the node_type: */
-
-	int  numdofs = -1;   //default numdofs
-	int *doftype = NULL;
-
-	/*ok, according to analysis type: */
-	switch(analysis_type){
-		case StressbalanceAnalysisEnum:
-			switch(node_type){
-				case SSAApproximationEnum:
-					numdofs=2;
-					break;
-				case L1L2ApproximationEnum:
-					numdofs=2;
-					break;
-				case HOApproximationEnum:
-					numdofs=2;
-					break;
-				case SIAApproximationEnum:
-					numdofs=2;
-					break;
-				case FSvelocityEnum:
-					numdofs=3;
-					break;
-				case FSpressureEnum:
-					numdofs=1;
-					break;
-				case NoneApproximationEnum:
-					numdofs=4;
-					break;
-				case SSAHOApproximationEnum:
-					numdofs=4;
-					doftype=xNew<int>(numdofs);
-					doftype[0]=SSAApproximationEnum;
-					doftype[1]=SSAApproximationEnum;
-					doftype[2]=HOApproximationEnum;
-					doftype[3]=HOApproximationEnum;
-					break;
-				case HOFSApproximationEnum:
-					numdofs=5;
-					doftype=xNew<int>(numdofs);
-					doftype[0]=HOApproximationEnum;
-					doftype[1]=HOApproximationEnum;
-					doftype[2]=FSvelocityEnum;
-					doftype[3]=FSvelocityEnum;
-					doftype[4]=FSvelocityEnum;
-					break;
-				case SSAFSApproximationEnum:
-					numdofs=5;
-					doftype=xNew<int>(numdofs);
-					doftype[0]=SSAApproximationEnum;
-					doftype[1]=SSAApproximationEnum;
-					doftype[2]=FSvelocityEnum;
-					doftype[3]=FSvelocityEnum;
-					doftype[4]=FSvelocityEnum;
-					break;
-				default:
-					_error_("Approximationtype " << node_type << " (" << EnumToStringx(node_type) << ") not implemented yet for StressbalanceHoriz");
-
-			}
-			break;
-		case StressbalanceVerticalAnalysisEnum:
-			numdofs=1;
-			break;
-		case StressbalanceSIAAnalysisEnum:
-			numdofs=2;
-			break;
-		case BedSlopeAnalysisEnum:
-			numdofs=1;
-			break;
-		case SurfaceSlopeAnalysisEnum:
-			numdofs=1;
-			break;
-		case ThermalAnalysisEnum:
-			numdofs=1;
-			break;
-		case EnthalpyAnalysisEnum:
-			numdofs=1;
-			break;
-		case HydrologyDCInefficientAnalysisEnum:
-			numdofs=1;
-			break;
-		case HydrologyDCEfficientAnalysisEnum:
-			numdofs=1;
-			break;
-		case HydrologyShreveAnalysisEnum:
-			numdofs=1;
-			break;
-		case MeltingAnalysisEnum:
-			numdofs=1;
-			break;
-		case MasstransportAnalysisEnum:
-			numdofs=1;
-			break;
-		case FreeSurfaceTopAnalysisEnum:
-			numdofs=1;
-			break;
-		case FreeSurfaceBaseAnalysisEnum:
-			numdofs=1;
-			break;
-		case GiaAnalysisEnum:
-			numdofs=1;
-			break;
-		case BalancethicknessAnalysisEnum:
-			numdofs=1;
-			break;
-		case BalancevelocityAnalysisEnum:
-			numdofs=1;
-			break;
-		default:
-			_error_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
-	}
-
-	/*Now initialize the index*/
-	index->Init(numdofs,doftype);
-
-	/*Clean up*/
-	 xDelete<int>(doftype);
-}
Index: /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 16560)
@@ -18,8 +18,11 @@
 
 	/*Mesh dependent variables*/
-	if(iomodel->dim==2){
+	if(iomodel->meshtype==Mesh2DhorizontalEnum){
 		elementnbe = 3;
 	}
-	else if(iomodel->dim==3){
+	else if(iomodel->meshtype==Mesh2DverticalEnum){
+		elementnbe = 3;
+	}
+	else if(iomodel->meshtype==Mesh3DEnum){
 		elementnbe = 9;
 	}
Index: /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 16560)
@@ -19,6 +19,5 @@
 	int i;
 
-	int my_rank;
-	int num_procs;
+	const int RIFTINFOSIZE = 12;
 	int numberofelements2d;
 	int numberofvertices2d;
@@ -41,27 +40,40 @@
 
 	/*Get my_rank:*/
-	my_rank   = IssmComm::GetRank();
-	num_procs = IssmComm::GetSize();
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
 
 	/*Fetch parameters: */
-	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;
+	if(*pmy_elements)return;
 
 	/*Number of vertices per elements, needed to correctly retrieve data: */
 	/*Determine parallel partitioning of elements: we use Metis for now. First load the data, then partition*/
-	if(iomodel->dim==2){
-		elements_width=3; //tria elements
-	}
-	else{
-		elements_width=6; //penta elements
-		iomodel->FetchData(&elements2d,NULL,NULL,MeshElements2dEnum);
+	switch(iomodel->meshtype){
+		case Mesh2DhorizontalEnum:
+			elements_width=3;
+			numberofelements2d = 0;
+			numberofvertices2d = 0;
+			numlayers          = 0;
+			break;
+		case Mesh2DverticalEnum:
+			elements_width=3;
+			numberofelements2d = 0;
+			numberofvertices2d = 0;
+			numlayers          = 0;
+			break;
+		case Mesh3DEnum:
+			elements_width=6; //penta elements
+			iomodel->FetchData(&elements2d,NULL,NULL,MeshElements2dEnum);
+			iomodel->Constant(&numberofelements2d,MeshNumberofelements2dEnum);
+			iomodel->Constant(&numberofvertices2d,MeshNumberofvertices2dEnum);
+			iomodel->Constant(&numlayers,MeshNumberoflayersEnum);
+			break;
+		default:
+			_error_("mesh not supported yet");
 	}
 
-	MeshPartitionx(&epart,&npart,iomodel->numberofelements,iomodel->numberofvertices,iomodel->elements,numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width,iomodel->dim,num_procs);
+	MeshPartitionx(&epart,&npart,iomodel->numberofelements,iomodel->numberofvertices,iomodel->elements,numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width,iomodel->meshtype,num_procs);
 
 	/*Free elements2d: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 16560)
@@ -15,5 +15,5 @@
 
 	/*Check Iomodel properties*/
-	if(iomodel->dim!=2) _error_("only 2d model are supported");
+	if(iomodel->meshtype!=Mesh2DhorizontalEnum) _error_("only 2d model are supported");
 
 	/*Get faces and elements*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 16560)
@@ -13,17 +13,17 @@
 #include "./ModelProcessorx.h"
 
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_list){
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,FILE* toolkitfile, char* rootpath,const int solution_enum,const int nummodels,const int* analysis_enum_list){
 
-	int   i,analysis_type,verbose;
+	int   i,analysis_enum,verbose;
 	bool  isthermal,ismasstransport,isstressbalance,isgroundingline,isenthalpy;
 
-	/*output: */
-	Elements    *elements    = NULL;
-	Nodes       *nodes       = NULL;
-	Vertices    *vertices    = NULL;
-	Materials   *materials   = NULL;
-	Constraints *constraints = NULL;
-	Loads       *loads       = NULL;
-	Parameters  *parameters  = NULL;
+	/*Initialize datasets*/
+	Elements    *elements    = new Elements();
+	Nodes       *nodes       = new Nodes();
+	Vertices    *vertices    = new Vertices();
+	Materials   *materials   = new Materials();
+	Constraints *constraints = new Constraints();
+	Loads       *loads       = new Loads();
+	Parameters  *parameters  = new Parameters();
 
 	/*Initialize IoModel from input file*/
@@ -42,29 +42,79 @@
 	if(VerboseMProcessor()) _printf0_("   starting model processor \n");
 
+	/*Partition Elements and Nodes*/
+	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
+
+	/*Create elements, vertices and materials, independent of analysis_enum: */
+	CreateElementsVerticesAndMaterials(elements,vertices,materials,iomodel,nummodels);
+
+	/*Create Parameters*/
+	CreateParameters(parameters,iomodel,rootpath,toolkitfile,solution_enum);
+
 	for(i=0;i<nummodels;i++){
 
-		analysis_type=analysis_type_list[i];
+		analysis_enum=analysis_enum_list[i];
+		parameters->AddObject(new IntParam(AnalysisCounterEnum,i));
 
 		/*Hack for trasient runs (FIXME: to be improved)*/
-		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum  && iomodel->dim==2) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum  && iomodel->dim==2) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==EnthalpyAnalysisEnum && iomodel->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==EnthalpyAnalysisEnum && isthermal==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum && isenthalpy==true) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==MasstransportAnalysisEnum && ismasstransport==false && isgroundingline==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceAnalysisEnum && isstressbalance==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceVerticalAnalysisEnum && isstressbalance==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceSIAAnalysisEnum && isstressbalance==false) continue;
-		if(solution_type==SteadystateSolutionEnum && analysis_type==ThermalAnalysisEnum && isenthalpy==true) continue;
-		if(solution_type==SteadystateSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
-		if(solution_type==SteadystateSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum  && iomodel->meshtype==Mesh2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum  && iomodel->meshtype==Mesh2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && iomodel->meshtype==Mesh2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MasstransportAnalysisEnum && ismasstransport==false && isgroundingline==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceVerticalAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceSIAAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
 
-		if(VerboseMProcessor()) _printf0_("   creating datasets for analysis " << EnumToStringx(analysis_type) << "\n");
-		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,rootpath,solution_type,analysis_type,nummodels,i);
+		if(VerboseMProcessor()) _printf0_("   creating datasets for analysis " << EnumToStringx(analysis_enum) << "\n");
+		Analysis* analysis = EnumToAnalysis(analysis_enum);
+		analysis->UpdateParameters(parameters,iomodel,solution_enum,analysis_enum);
+		analysis->CreateNodes(nodes,iomodel);
+		analysis->CreateConstraints(constraints,iomodel);
+		analysis->CreateLoads(loads,iomodel);
+		analysis->UpdateElements(elements,iomodel,i,analysis_enum);
+		delete analysis;
+
+
+		/* Update counters, because we have created more nodes, loads and
+		 * constraints, and ids for objects created in next call to CreateDataSets
+		 * will need to start at the end of the updated counters: */
+		iomodel->nodecounter       = nodes->MaximumId();
+		iomodel->loadcounter       = loads->NumberOfLoads();
+		iomodel->constraintcounter = constraints->NumberOfConstraints();
 	}
+
+	/*Solution specific updates*/
+	#ifdef _HAVE_CONTROL_
+	UpdateElementsAndMaterialsControl(elements,materials,iomodel);
+	#endif
+	#ifdef _HAVE_DAKOTA_
+	UpdateElementsAndMaterialsDakota(elements,materials,iomodel);
+	#endif
+	#ifdef _HAVE_TRANSIENT_
+	if(solution_enum==TransientSolutionEnum){
+		UpdateElementsTransient(elements,parameters,iomodel,analysis_enum);
+	}
+	#endif
+
+	/* Sort datasets:
+	 * All our datasets are already ordered by ids. Set presort flag so that
+	 * later on, when sorting is requested on these datasets, it will not be
+	 * redone: */
+	elements->Presort();
+	nodes->Presort();
+	vertices->Presort();
+	loads->Presort();
+	materials->Presort();
+
+	constraints->Presort();
+	parameters->Presort();
 	if(VerboseMProcessor()) _printf0_("   done with model processor \n");
 
@@ -73,11 +123,10 @@
 
 	/*Assign output pointers:*/
-	*pelements=elements;
-	*pnodes=nodes;
-	*pvertices=vertices;
-	*pmaterials=materials;
-	*pconstraints=constraints;
-	*ploads=loads;
-	*pparameters=parameters;
-
+	*pelements    = elements;
+	*pnodes       = nodes;
+	*pvertices    = vertices;
+	*pmaterials   = materials;
+	*pconstraints = constraints;
+	*ploads       = loads;
+	*pparameters  = parameters;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 16560)
@@ -6,125 +6,20 @@
 #define _MODEL_PROCESSORX_H_
 
-#define RIFTINFOSIZE 12
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
 
-#include "../../classes/classes.h"
-
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,FILE* toolkitfile, char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
 
 /*Creation of fem datasets: general drivers*/
-void CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
-void CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels);
-void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter);
-void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type);
-void CreateParametersHydrologyShreve(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void CreateParametersHydrologyDCInefficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void CreateParametersHydrologyDCEfficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials, IoModel* iomodel,const int nummodels);
+void CreateParameters(Parameters*parameters,IoModel* iomodel,char* rootpath,FILE* toolkitfile,const int solution_type);
+void CreateParametersAutodiff(Parameters* parameters,IoModel* iomodel);
+void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type);
+void CreateParametersDakota(Parameters* parameters,IoModel* iomodel,char* rootpath);
+void CreateOutputDefinitions(Parameters* parameters,IoModel* iomodel);
 void UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
-void CreateNodes(Nodes** pnodes, IoModel* iomodel,int analysis,int finite_element,int approximation=NoneApproximationEnum);
-
-/*Creation of fem datasets: specialised drivers: */
-
-/*stressbalance horizontal*/
-void CreateNodesStressbalance(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsStressbalance(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsStressbalance(Loads** ploads, IoModel* iomodel);
-void UpdateElementsStressbalance(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-
-/*stressbalance vertical*/
-void CreateNodesStressbalanceVertical(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsStressbalanceVertical(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsStressbalanceVertical(Loads** ploads, IoModel* iomodel);
-void UpdateElementsStressbalanceVertical(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-
-/*stressbalance SIA*/
-void CreateNodesStressbalanceSIA(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsStressbalanceSIA(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsStressbalanceSIA(Loads** ploads, IoModel* iomodel);
-void UpdateElementsStressbalanceSIA(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-
-#ifdef _HAVE_GIA_
-/*gia*/
-void CreateNodesGia(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsGia(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsGia(Loads** ploads, IoModel* iomodel);
-void UpdateElementsGia(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-#endif
-
-/*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 Shreve:*/
-void CreateNodesHydrologyShreve(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsHydrologyShreve(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsHydrologyShreve(Loads** ploads, IoModel* iomodel);
-void UpdateElementsHydrologyShreve(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-
-/*hydrology DC:*/
-void CreateNodesHydrologyDCInefficient(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsHydrologyDCInefficient(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsHydrologyDCInefficient(Loads** ploads, IoModel* iomodel);
-void UpdateElementsHydrologyDCInefficient(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-void CreateNodesHydrologyDCEfficient(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsHydrologyDCEfficient(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsHydrologyDCEfficient(Loads** ploads, IoModel* iomodel);
-void UpdateElementsHydrologyDCEfficient(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);
-
-/*masstransport:*/
-void CreateNodesMasstransport(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsMasstransport(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsMasstransport(Loads** ploads, IoModel* iomodel);
-void UpdateElementsMasstransport(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-void CreateNodesFreeSurfaceTop(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsFreeSurfaceTop(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsFreeSurfaceTop(Loads** ploads, IoModel* iomodel);
-void UpdateElementsFreeSurfaceTop(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-void CreateNodesFreeSurfaceBase(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsFreeSurfaceBase(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsFreeSurfaceBase(Loads** ploads, IoModel* iomodel);
-void UpdateElementsFreeSurfaceBase(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);
-
-/*balancedvelocity:*/
-void CreateNodesBalancevelocity(Nodes** pnodes,IoModel* iomodel);
-void CreateConstraintsBalancevelocity(Constraints** pconstraints,IoModel* iomodel);
-void CreateLoadsBalancevelocity(Loads** ploads, IoModel* iomodel);
-void UpdateElementsBalancevelocity(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);
+void UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel);
+void UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_type);
+void CreateNodes(Nodes*nodes, IoModel* iomodel,int analysis,int finite_element,int approximation=NoneApproximationEnum);
 
 /*partitioning: */
@@ -141,11 +36,3 @@
 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,int node_type);
-
 #endif
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 16560)
@@ -46,5 +46,4 @@
 	/*Intermediaries*/
 	int  i,i1,i2;
-	int  cols;
 	int  e1,e2;
 	int  pos;
@@ -66,5 +65,5 @@
 
 	/*First: add all the nodes of all the elements belonging to this cpu*/
-	if(iomodel->dim==2){
+	if(iomodel->meshtype==Mesh2DhorizontalEnum){
 		for (i=0;i<iomodel->numberofelements;i++){
 			if (my_elements[i]){
Index: sm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 16559)
+++ 	(revision )
@@ -1,45 +1,0 @@
-/*!\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 "../../classes/classes.h"
-#include "../../shared/shared.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/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 16560)
@@ -9,4 +9,11 @@
 #include "../ModelProcessorx.h"
 
-void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type){
+void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_type){
+
+	bool isgroundingline;
+	parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+
+	if(isgroundingline){
+		iomodel->FetchDataToInput(elements,BathymetryEnum);
+	}
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 16559)
+++ 	(revision )
@@ -1,35 +1,0 @@
-/*!\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 "../../classes/classes.h"
-#include "../../shared/shared.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->MaximumId();
-	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/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 16560)
@@ -10,15 +10,7 @@
 void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
-	int my_rank;
-	int i;
-	int index;
-	Element* element=NULL;
 	IssmDouble value;
-	int found;
-	int sumfound;
-	int cpu_found;
-
-	/*Get my_rank:*/
-	my_rank=IssmComm::GetRank();
+	int        index;
+	int        found,sumfound,cpu_found;
 
 	/*retrieve element we are interested in: */
@@ -27,9 +19,9 @@
 	/*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++){
+	for(int i=0;i<elements->Size();i++){
 		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		found=element->NodalValue(&value,index,natureofdataenum);
-		if (found){
-			cpu_found=my_rank;
+		if(found){
+			cpu_found=IssmComm::GetRank();
 			break;
 		}
@@ -37,5 +29,5 @@
 
 	/*Broadcast whether we found the element: */
-	ISSM_MPI_Allreduce ( &found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce(&found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
 
Index: /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 16560)
+++ /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 16560)
@@ -0,0 +1,37 @@
+/*!\file OutputDefinitionsResponsex
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./OutputDefinitionsResponsex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string){
+
+	Definition *definition         = NULL;
+	DataSet    *output_definitions = NULL;
+	IssmDouble  return_value;
+
+	/*Ok, go find the output definitions dataset in the parameters, where our responses are hiding: */
+	femmodel->parameters->FindParam(&output_definitions,OutputdefinitionEnum); _assert_(output_definitions);
+
+	/*Now, go through the output definitions, and retrieve the object which corresponds to our requested response, output_string: */
+	for(int i=0;i<output_definitions->Size();i++){
+		
+		definition=dynamic_cast<Definition*>(output_definitions->GetObjectByOffset(i));
+
+		char* name = definition->Name();
+		if (strcmp(name,output_string)==0){
+			/*This is the object that we have been chasing for. compute the response and return: */
+			return_value=definition->Response(femmodel);
+			delete output_definitions;
+			xDelete<char>(name);
+			return return_value;
+		}
+		xDelete<char>(name);
+	}
+	/*If we are here, did not find the definition for this response, not good!: */
+	_error_("Could not find the response for output definition " << output_string << " because could not find the definition itself!");
+
+}
Index: /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h
===================================================================
--- /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 16560)
+++ /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 16560)
@@ -0,0 +1,12 @@
+/*!\file:  OutputDefinitionsResponsexx.h
+*/ 
+
+#ifndef _OUTPUTDEFINITIONSRESPONSEXX_H
+#define _OUTPUTDEFINITIONSRESPONSEXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string);
+
+#endif  /* _OUTPUTDEFINITIONSRESPONSEXX_H */
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 16560)
@@ -37,8 +37,4 @@
 	}
 
-	/*We have results inside our elements, loads, etc ... Get them out of there, into the results dataset: */
-	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: */
@@ -46,5 +42,5 @@
 		parameters->FindParam(&solutiontype,SolutionTypeEnum);
 		EnumToStringx(&solutiontypestring,solutiontype);
-		results->AddObject(new GenericExternalResult<char*>(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
+		results->AddResult(new GenericExternalResult<char*>(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
 		xDelete<char>(solutiontypestring);
 	}
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 16560)
@@ -11,19 +11,14 @@
 
 	/*threading: */
-	PointCloudFindNeighborsThreadStruct gate;
-	int num=1;
-
-	#ifdef _MULTITHREADING_
-	num=_NUMTHREADS_;
-	#endif
-
+	int num=_NUMTHREADS_;
 	if(!multithread)num=1;
 
 	/*initialize thread parameters: */
-	gate.x=x;
-	gate.y=y;
-	gate.nods=nods;
-	gate.mindistance=mindistance;
-	gate.flags=flags;
+	PointCloudFindNeighborsThreadStruct gate;
+	gate.x           = x;
+	gate.y           = y;
+	gate.nods        = nods;
+	gate.mindistance = mindistance;
+	gate.flags       = flags;
 
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
Index: /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp	(revision 16560)
@@ -11,11 +11,5 @@
 	int i;
 	Element* element=NULL;
-
-	/*drain excess water fraction: */
-	for (i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->DrainWaterfraction();
-	}
-
+	
 	/*Compute basal melting rates: */
 	for (i=0;i<femmodel->elements->Size();i++){
@@ -24,8 +18,15 @@
 	}
 
+	/*drain excess water fraction: */
+	/*for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->DrainWaterfraction();
+	}
+	*/
+
 	/*Update basal dirichlet BCs for enthalpy: */
 	for (i=0;i<femmodel->elements->Size();i++){
 		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->UpdateThermalBasalConstraints();
+		element->UpdateBasalConstraintsEnthalpy();
 	}
 }
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 16560)
@@ -16,5 +16,4 @@
 void ResetConstraintsx(FemModel* femmodel){
 
-
 	/*Display message*/
 	if(VerboseModule()) _printf0_("   Resetting penalties\n");
@@ -24,6 +23,5 @@
 	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
-	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
-	 * management routine, otherwise, skip : */
+	/*Deal with rift first*/
 	#ifdef _HAVE_RIFTS_
 	if(RiftIsPresent(femmodel->loads,analysis_type)){
@@ -31,8 +29,14 @@
 	}
 	#endif
-	#ifdef _HAVE_THERMAL_
-	if(ThermalIsPresent(femmodel->loads,analysis_type)){
-		ThermalConstraintsReset(femmodel->loads,analysis_type);
+
+	/*Reset pengrid to inactive mode*/
+	for(int i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(analysis_type)){
+			if(load->ObjectEnum()==PengridEnum){
+				Pengrid* pengrid=(Pengrid*)load;
+				pengrid->ResetConstraint();
+			}
+		}
 	}
-	#endif
 }
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 16560)
@@ -9,5 +9,4 @@
 
 /* local prototypes: */
-void ThermalConstraintsReset(Loads* loads, int configuration_type);
 void ResetConstraintsx(FemModel* femmodel);
 
Index: sm/trunk/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp	(revision 16559)
+++ 	(revision )
@@ -1,29 +1,0 @@
-/*!\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/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters, int weight_index){
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->RheologyBbarAbsGradient(weight_index);
+		J+=element->RheologyBbarAbsGradient();
 	}
 
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/Scotchx/Scotchx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Scotchx/Scotchx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Scotchx/Scotchx.cpp	(revision 16560)
@@ -260,5 +260,5 @@
     }
   }
-  if ((flagval & C_FLAGPART) != 0) {              /* If program run as the partitioner            */
+  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;
@@ -305,10 +305,10 @@
   clockStop (&runtime[0]);                        /* Get output time */
 
-  if (flagval & C_FLAGVERBSTR) {
+  if (flagval && C_FLAGVERBSTR) {
     fprintf (C_filepntrlogout, "S\tStrat=");
     SCOTCH_stratSave (&stradat, C_filepntrlogout);
     putc ('\n', C_filepntrlogout);
   }
-  if (flagval & C_FLAGVERBTIM) {
+  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]),
@@ -317,5 +317,5 @@
              (double) clockVal (&runtime[1]));
   }
-  if (flagval & C_FLAGVERBMAP)
+  if (flagval && C_FLAGVERBMAP)
     SCOTCH_graphMapView (&grafdat, &mapdat, C_filepntrlogout);
 
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 16560)
@@ -8,16 +8,12 @@
 #include "../../kml/kmlobjects.h"
 
-int Shp2Kmlx(char* filshp,char* filkml,
-			 int sgn){
+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));
+	Xy2lldef(&cm,&sp,sgn);
+
+	return(Shp2Kmlx(filshp,filkml,sgn,cm,sp));
 
 	#else //ifdef _HAVE_SHAPELIB_
@@ -26,6 +22,5 @@
 }
 
-int Shp2Kmlx(char* filshp,char* filkml,
-			 int sgn,double cm,double sp){
+int Shp2Kmlx(char* filshp,char* filkml,int sgn,double cm,double sp){
 
 	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
@@ -103,9 +98,6 @@
 	pshapm=xNew<double*>(nshape);
 
-/*  loop over the list of shapes  */
-
-	for( i = 0; i < nEntities; i++ )
-	{
-//	int     j;
+	/* loop over the list of shapes  */
+	for(i=0;i<nEntities;i++ ){
 		SHPObject   *psShape;
 
@@ -231,5 +223,5 @@
 	sprintf(klsty->color     ,"ff000000");
 	sprintf(klsty->colormode ,"normal");
-	klsty->width     ,lwidth;
+	klsty->width     =lwidth;
 	kpsty =new KML_PolyStyle();
 	sprintf(kpsty->color     ,"00ffffff");
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceAbsVelMisfit(weight_index);
+		J+=element->SurfaceAbsVelMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 16560)
@@ -9,5 +9,5 @@
 #include "../SurfaceAreax/SurfaceAreax.h"
 
-void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel,int weight_index){
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel){
 
 	/*Intermediary*/
@@ -24,5 +24,5 @@
 	for(int i=0;i<femmodel->elements->Size();i++){
 		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		J+=element->SurfaceAverageVelMisfit(weight_index);
+		J+=element->SurfaceAverageVelMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel,int weight_index);
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceLogVelMisfit(weight_index);
+		J+=element->SurfaceLogVelMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceLogVxVyMisfit(weight_index);
+		J+=element->SurfaceLogVxVyMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceRelVelMisfit(weight_index);
+		J+=element->SurfaceRelVelMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters, int weight_index){
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAbsMisfit(weight_index);
+		J+=element->ThicknessAbsMisfit();
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAcrossGradient(weight_index);
+		J+=element->ThicknessAcrossGradient();
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 16560)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -21,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAlongGradient(weight_index);
+		J+=element->ThicknessAlongGradient();
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 16559)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 16560)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 16559)
+++ /issm/trunk/src/c/modules/modules.h	(revision 16560)
@@ -44,5 +44,4 @@
 #include "./InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h"
 #include "./InterpFromMeshToGridx/InterpFromMeshToGridx.h"
-#include "./InputToResultx/InputToResultx.h"
 #include "./InputUpdateFromConstantx/InputUpdateFromConstantx.h"
 #include "./InputUpdateFromSolutionx/InputUpdateFromSolutionx.h"
@@ -51,5 +50,4 @@
 #include "./InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
 #include "./InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h"
-#include "./InputArtificialNoisex/InputArtificialNoisex.h"
 #include "./IoModelToConstraintsx/IoModelToConstraintsx.h"
 #include "./KMLFileReadx/KMLFileReadx.h"
@@ -73,4 +71,5 @@
 #include "./NodesDofx/NodesDofx.h"
 #include "./Orthx/Orthx.h"
+#include "./OutputDefinitionsResponsex/OutputDefinitionsResponsex.h"
 #include "./OutputResultsx/OutputResultsx.h"
 #include "./ConstraintsStatex/ConstraintsStatex.h"
@@ -86,5 +85,4 @@
 #include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
 #include "./Scotchx/Scotchx.h"
-#include "./Shp2Expx/Shp2Expx.h"
 #include "./Shp2Kmlx/Shp2Kmlx.h"
 #include "./SmbGradientsx/SmbGradientsx.h"
Index: /issm/trunk/src/c/shared/Bamg/HeapSort.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 16560)
@@ -85,4 +85,7 @@
 		}
 	}
+
+	/*Make cppcheck happy*/
+	*porder=order;
 }/*}}}*/
 
Index: /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 16560)
@@ -16,11 +16,10 @@
   IssmDouble delta18oLapseRate=-6.2*pow(10.,-3);
   IssmDouble glacialindex; // used to vary present day temperature
-  int imonth=0;
 
-  glacialindex = 0;//(Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
+  glacialindex = 0.;//(Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
   //  /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent));
 
   for (int imonth = 0; imonth<12; imonth++){  
-    monthlytemperaturestmp[imonth] = glacialindex*TemperaturesLgm[imonth] + (1-glacialindex)*TemperaturesPresentday[imonth];
+    monthlytemperaturestmp[imonth] = glacialindex*TemperaturesLgm[imonth] + (1.-glacialindex)*TemperaturesPresentday[imonth];
     //monthlyprectmp[imonth] = 1.5*pow(2,((monthlytemperaturestmp[imonth]-273.15-0)/10)); //equation from rob's paper
     monthlyprectmp[imonth] = PrecipitationsPresentday[imonth];
Index: /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 16560)
@@ -9,35 +9,37 @@
 /*FUNCTION IssmDouble DrainageFunctionWaterfraction()*/
 IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.){
-    /* DrainageFunctionWaterfraction returns how much of the waterfraction is drained per year */
-    _assert_(waterfraction>=0.);
-    _assert_(dt>=0.);
+	/* DrainageFunctionWaterfraction returns how much of the waterfraction is drained per year */
+	_assert_(waterfraction>=0.);
+	_assert_(dt>=0.);
 
-    IssmDouble w0=0.01, w1=0.02, w2=0.03;
-    IssmDouble Dret, D0=0, D1=0.005, D2=0.05;
+	IssmDouble w0=0.01, w1=0.02, w2=0.03;
+	IssmDouble Dret, D0=0, D1=0.005, D2=0.05;
+	IssmDouble yts=365*24*60*60;
+	dt/=yts;
 
-    /*get drainage function value*/
-    if((w0==w1)||(w1==w2)||(w0==w2))
-        _error_("Error: equal ordinates in DrainageFunctionWaterfraction -> division by zero. Abort");
-    if(waterfraction<=w0)
-        Dret=D0;
-    if((waterfraction>w0) && (waterfraction<=w1))
-        Dret=(D1-D0)/(w1-w0)*(waterfraction-w0)+D0;
-    if((waterfraction>w1) && (waterfraction<=w2))
-        Dret=(D2-D1)/(w2-w1)*(waterfraction-w1)+D1;
-    else 
-        Dret=D2;
-    
-    /*check if dt*Dret>waterfraction. If so, drain whole waterfraction*/
-    if(dt==0.){
-      if(Dret>waterfraction)
-        return waterfraction;
-      else
-        return Dret;
-    }
-    else{
-      if(dt*Dret>waterfraction)
-        return waterfraction;
-      else
-        return dt*Dret;
-    }
+	/*get drainage function value*/
+	if((w0==w1)||(w1==w2)||(w0==w2))
+		_error_("Error: equal ordinates in DrainageFunctionWaterfraction -> division by zero. Abort");
+	if(waterfraction<=w0)
+		Dret=D0;
+	if((waterfraction>w0) && (waterfraction<=w1))
+		Dret=(D1-D0)/(w1-w0)*(waterfraction-w0)+D0;
+	if((waterfraction>w1) && (waterfraction<=w2))
+		Dret=(D2-D1)/(w2-w1)*(waterfraction-w1)+D1;
+	else 
+		Dret=D2;
+
+	/*check if dt*Dret>waterfraction. If so, drain whole waterfraction*/
+	if(dt==0.){
+		if(Dret>waterfraction)
+			return waterfraction;
+		else
+			return Dret;
+	}
+	else{
+		if(dt*Dret>waterfraction)
+			return waterfraction;
+		else
+			return dt*Dret;
+	}
 }
Index: /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp	(revision 16560)
@@ -7,8 +7,7 @@
 #include "../Exceptions/exceptions.h"
 
-
 /* get ice stiffness B from enthalpy, pressure and flow law exponent*/
-IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n){
-  /*Use parameterization for the rheology: Aschwanden 2012
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure, IssmDouble n, IssmDouble betaCC, IssmDouble referencetemperature, IssmDouble heatcapacity, IssmDouble latentheat){
+  /*Use parameterization for the rheology: Grewe/Blatter 2009, Aschwanden 2012
    *
    *  A(H,p) = A0 exp(-Q/RT(H,p)), if H < H_s(p)
@@ -23,5 +22,5 @@
    *  H_s(p) = c_i (Tpmp - Tref)
    *
-   *  Tpmp   = T - beta p;
+   *  Tpmp   = T - betaCC p;
    *
    *  A0 constant of proportionality
@@ -35,22 +34,23 @@
    *  
    *  Convert A to B :  B = A^(-1/n) */
-  
-  /*Some physical constants (Aschwanden 2012)*/
-  /*TODO: get those constants from model*/
-  IssmDouble beta=7.9*pow(10.,-8.);
-  IssmDouble R=8.314;
-  IssmDouble heatcapacity=2009; // J/kg/K
-  IssmDouble Tref=253.15;
-  IssmDouble latentheat=3.34*pow(10,5.); // from Aschwanden 2012
+
+	/*check feasibility*/
+  _assert_(pressure>0);
+  _assert_(n>0);
+  _assert_(betaCC>0);
+  _assert_(referencetemperature>0);
+  _assert_(heatcapacity>0);
+  _assert_(latentheat>0);
+
+  /*Some physical constants*/
+  IssmDouble R=8.314; 
 
   /*Intermediaries*/
   IssmDouble A,B,Tstar,Tpmp,H_sp,waterfraction;
-	
-  _assert_(pressure>0);
-  _assert_(enthalpy>0);
-  Tpmp=273.15-beta*pressure; 
-  H_sp=heatcapacity*(Tpmp - Tref);
+
+  Tpmp=273.15-betaCC*pressure; 
+  H_sp=heatcapacity*(Tpmp - referencetemperature);
   if (enthalpy < H_sp){
-    Tstar = Tref + enthalpy/heatcapacity - beta*pressure;	
+    Tstar = referencetemperature + enthalpy/heatcapacity - betaCC*pressure;	
     waterfraction = 0;
   }
@@ -76,35 +76,36 @@
 }
 
-/*Get stiffness from temperature, waterfraction and depth*/
-IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n){
-	/*Use parameterization for the rheology: Greve and Blatter 2009
-	 * get enthalpy from temperature and water fraction,
-	 * and use LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n) */
-  
-  IssmDouble rho_ice=910; // kg/m^3
-  IssmDouble g=9.81; //kg*m/s^2
-  IssmDouble heatcapacity=2009; // J/kg/K
-  IssmDouble Tref=253.15;
-  IssmDouble beta=7.9*pow(10.,-8.);
-  IssmDouble latentheat=3.34*pow(10,5.); // from Aschwanden 2012
-  IssmDouble Tstar, enthalpy, pressure, B;
-  _assert_(temperature>0);
-  _assert_(waterfraction>0);
-  _assert_(depth>0);
-
-  /*get pressure*/
-  pressure= rho_ice*g*depth;
-  Tstar=temperature-beta*pressure; // TODO: check whether plus or minus
-  /*get enthalpy*/
-  if (Tstar < 273.15){
-    enthalpy=heatcapacity*(Tstar - Tref);
-  }
-  else{
-    enthalpy=heatcapacity*(273.15 - Tref) + waterfraction*latentheat;
-  }
-	
-  B=LliboutryDuval(enthalpy, pressure, n);
-
-  return B;
-}
-
+// /*Get stiffness from temperature, waterfraction and depth*/
+// IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n){
+// 	/*Use parameterization for the rheology: Greve and Blatter 2009
+// 	 * get enthalpy from temperature and water fraction,
+// 	 * and use LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n) */
+// 
+// 	/*TODO: update params from model*/
+//   IssmDouble rho_ice=910; // kg/m^3
+//   IssmDouble g=9.81; //kg*m/s^2
+//   IssmDouble heatcapacity=2009; // J/kg/K
+//   IssmDouble referencetemperature=253.15;
+//   IssmDouble betaCC=7.9*pow(10.,-8.);
+//   IssmDouble latentheat=3.34*pow(10,5.); // from Aschwanden 2012
+// 
+//   IssmDouble Tstar, enthalpy, pressure, B;
+//   _assert_(temperature>0);
+//   _assert_(waterfraction>0);
+//   _assert_(depth>0);
+// 
+//   /*get pressure*/
+//   pressure= rho_ice*g*depth;
+//   Tstar=temperature-betaCC*pressure; // TODO: check whether plus or minus
+//   /*get enthalpy*/
+//   if (Tstar < 273.15){
+//     enthalpy=heatcapacity*(Tstar - referencetemperature);
+//   }
+//   else{
+//     enthalpy=heatcapacity*(273.15 - referencetemperature) + waterfraction*latentheat;
+//   }
+// 
+//   B=LliboutryDuval(enthalpy, pressure, n, betaCC, referencetemperature, heatcapacity, latentheat);
+// 
+//   return B;
+// }
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 16560)
@@ -10,6 +10,6 @@
 IssmDouble Paterson(IssmDouble temperature);
 IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n);
-IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n);
-IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n);
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure, IssmDouble n, IssmDouble betaCC, IssmDouble referencetemperature, IssmDouble heatcapacity, IssmDouble latentheat);
+// IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n);
 IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, 
 				IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s,
Index: /issm/trunk/src/c/shared/Enum/Enum.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/Enum.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Enum/Enum.h	(revision 16560)
@@ -6,5 +6,5 @@
 const char* EnumToStringx(int enum_in);
 void        EnumToStringx(char** string,int enum_in);
-int         StringToEnumx(const char* string_in);
+int         StringToEnumx(const char* string_in,bool notfounderror=true);
 
 #endif
Index: /issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 16560)
@@ -29,4 +29,10 @@
 	AutodiffMassFluxSegmentsPresentEnum,
 	AutodiffKeepEnum,
+	AutodiffObufsizeEnum,
+	AutodiffLbufsizeEnum,
+	AutodiffCbufsizeEnum,
+	AutodiffTbufsizeEnum,
+	AutodiffGcTriggerRatioEnum,
+	AutodiffGcTriggerMaxSizeEnum,
 	BalancethicknessSpcthicknessEnum,
 	BalancethicknessStabilizationEnum,
@@ -42,11 +48,10 @@
 	DependentObjectEnum,
 	StressbalanceAbstolEnum,
-	StressbalanceIcefrontEnum,
 	StressbalanceIsnewtonEnum,
 	StressbalanceMaxiterEnum,
-	StressbalanceNumRequestedOutputsEnum,
 	StressbalancePenaltyFactorEnum,
 	StressbalanceReferentialEnum,
 	StressbalanceReltolEnum,
+	StressbalanceNumRequestedOutputsEnum,
 	StressbalanceRequestedOutputsEnum,
 	StressbalanceRestolEnum,
@@ -118,5 +123,4 @@
 	HydrologyEfficientEnum,
 	HydrologySedimentKmaxEnum,
-	BasisIntegralEnum,
 	WaterTransferEnum,
 	IndependentObjectEnum,
@@ -125,5 +129,4 @@
 	InversionCostFunctionsCoefficientsEnum,
 	InversionCostFunctionsEnum,
-	InversionGradientOnlyEnum,
 	InversionGradientScalingEnum,
 	InversionIscontrolEnum,
@@ -138,9 +141,9 @@
 	InversionStepThresholdEnum,
 	InversionThicknessObsEnum,
-	InversionVelObsEnum,
 	InversionVxObsEnum,
 	InversionVyObsEnum,
 	InversionVzObsEnum,
 	MaskIceLevelsetEnum,
+	QmuMaskIceLevelsetEnum,
 	MaterialsBetaEnum,
 	MaterialsHeatcapacityEnum,
@@ -152,6 +155,21 @@
 	MaterialsRheologyLawEnum,
 	MaterialsRheologyNEnum,
-	MaterialsRheologyZEnum,
-	MaterialsRheologyZbarEnum,
+	DamageDEnum,
+	QmuDamageDEnum,
+	DamageDbarEnum,
+	DamageLawEnum,
+	DamageC1Enum,
+	DamageC2Enum,
+	DamageC3Enum,
+	DamageC4Enum,
+	DamageHealingEnum,
+	DamageStressThresholdEnum,
+	DamageStabilizationEnum,
+	DamagePenaltyThresholdEnum,
+	DamagePenaltyLockEnum,
+	DamagePenaltyFactorEnum,
+	DamageMaxiterEnum,
+	DamageSpcdamageEnum,
+	DamageMaxDamageEnum,
 	MaterialsRhoIceEnum,
 	MaterialsRhoWaterEnum,
@@ -165,5 +183,4 @@
 	MaterialsMantleDensityEnum,
 	MeshAverageVertexConnectivityEnum,
-	MeshDimensionEnum,
 	MeshElementonbedEnum,
 	MeshElementonsurfaceEnum,
@@ -182,4 +199,8 @@
 	MeshYEnum,
 	MeshZEnum,
+	MeshTypeEnum,
+	Mesh2DhorizontalEnum,
+	Mesh2DverticalEnum,
+	Mesh3DEnum,
 	MiscellaneousNameEnum, //FIXME: only used by qmu, should not be marshalled (already in queueing script)
 	MasstransportHydrostaticAdjustmentEnum,
@@ -207,5 +228,4 @@
 	SettingsLowmemEnum,
 	SettingsOutputFrequencyEnum,
-	SettingsResultsAsPatchesEnum,
 	SettingsWaitonlockEnum,
 	SurfaceforcingsDelta18oEnum,
@@ -237,5 +257,5 @@
 	SurfaceforcingsBNegEnum,
 	ThermalIsenthalpyEnum,
-    	ThermalIsdynamicbasalspcEnum,
+	ThermalIsdynamicbasalspcEnum,
 	ThermalMaxiterEnum,
 	ThermalPenaltyFactorEnum,
@@ -244,4 +264,6 @@
 	ThermalSpctemperatureEnum,
 	ThermalStabilizationEnum,
+	ThermalNumRequestedOutputsEnum,
+	ThermalRequestedOutputsEnum,
 	GiaMantleViscosityEnum,
 	GiaLithosphereThicknessEnum,
@@ -257,4 +279,5 @@
 	TransientIsthermalEnum,
 	TransientIsgiaEnum,
+	TransientIsdamageEnum,
 	TransientNumRequestedOutputsEnum,
 	TransientRequestedOutputsEnum,
@@ -266,7 +289,5 @@
 	AdjointBalancethicknessAnalysisEnum,
 	AdjointHorizAnalysisEnum,
-	AdjointSolutionEnum,
 	AnalysisCounterEnum,
-	NoneAnalysisEnum,
 	DefaultAnalysisEnum,
 	BalancethicknessAnalysisEnum,
@@ -276,8 +297,8 @@
 	BalancevelocityAnalysisEnum,
 	BalancevelocitySolutionEnum,
-	BedSlopeAnalysisEnum,
+	L2ProjectionBaseAnalysisEnum,
 	BedSlopeSolutionEnum,
-	BedSlopeXAnalysisEnum,
-	BedSlopeYAnalysisEnum,
+	DamageEvolutionSolutionEnum,
+	DamageEvolutionAnalysisEnum,
 	StressbalanceAnalysisEnum,
 	StressbalanceSIAAnalysisEnum,
@@ -285,5 +306,4 @@
 	StressbalanceVerticalAnalysisEnum,
 	EnthalpyAnalysisEnum,
-	EnthalpySolutionEnum,
 	FlaimAnalysisEnum,
 	FlaimSolutionEnum,
@@ -297,9 +317,9 @@
 	FreeSurfaceBaseAnalysisEnum,
 	FreeSurfaceTopAnalysisEnum,
+	ExtrudeFromBaseAnalysisEnum,
+	ExtrudeFromTopAnalysisEnum,
 	SteadystateSolutionEnum,
-	SurfaceSlopeAnalysisEnum,
+	L2ProjectionTopAnalysisEnum,
 	SurfaceSlopeSolutionEnum,
-	SurfaceSlopeXAnalysisEnum,
-	SurfaceSlopeYAnalysisEnum,
 	SmoothedSurfaceSlopeXAnalysisEnum,
 	SmoothedSurfaceSlopeYAnalysisEnum,
@@ -309,4 +329,6 @@
 	GiaSolutionEnum,
 	GiaAnalysisEnum,
+	MeshdeformationSolutionEnum,
+	MeshdeformationAnalysisEnum,
 	/*}}}*/
 	/*Approximations {{{*/
@@ -342,5 +364,4 @@
 	ControlInputEnum,
 	DatasetInputEnum,
-	DofIndexingEnum,
 	DoubleInputEnum,
 	DataSetParamEnum,
@@ -350,19 +371,14 @@
 	DoubleVecParamEnum,
 	ElementEnum,
-	ElementResultEnum,
 	ExternalResultEnum,
 	FileParamEnum,
-	HookEnum,
-	IcefrontEnum,
 	InputEnum,
 	IntInputEnum,
+	InputToExtrudeEnum,
+	InputToL2ProjectEnum,
 	IntParamEnum,
 	IntVecParamEnum,
 	TransientParamEnum,
-	IceFrontTypeEnum,
-	SSA2dIceFrontEnum,
-	SSA3dIceFrontEnum,
 	MaticeEnum,
-	MatdamageiceEnum,
 	MatparEnum,
 	NodeEnum,
@@ -370,6 +386,4 @@
 	NumericalfluxTypeEnum,
 	ParamEnum,
-	L1L2IceFrontEnum,
-	HOIceFrontEnum,
 	PengridEnum,
 	PenpairEnum,
@@ -387,7 +401,8 @@
 	SpcStaticEnum,
 	SpcTransientEnum,
-	FSIceFrontEnum,
 	StringArrayParamEnum,
 	StringParamEnum,
+	SegEnum,
+	SegInputEnum,
 	TriaEnum,
 	TriaInputEnum,
@@ -416,5 +431,4 @@
 	BedSlopeYEnum,
 	BoundaryEnum,
-	ConstantEnum,
 	ConvergedEnum,
 	FillEnum,
@@ -424,8 +438,6 @@
 	InternalEnum,
 	MassFluxEnum,
-	MaxPenetrationEnum,
 	MeltingOffsetEnum,
 	MisfitEnum,
-	NumberNodeToElementConnectivityEnum,
 	PressureEnum,
 	PressurePicardEnum,
@@ -453,5 +465,4 @@
 	SurfaceSlopeYEnum,
 	TemperatureEnum,
-	TemperatureOldEnum,
 	TemperaturePicardEnum,
 	ThicknessAbsMisfitEnum,
@@ -477,5 +488,4 @@
 	ThicknessAlongGradientEnum,
 	ThicknessAcrossGradientEnum,
-	StepResponsesEnum,
 	IntMatParamEnum,
 	RheologyBbarAbsGradientEnum,
@@ -517,20 +527,20 @@
 	/*Results{{{*/
 	SaveResultsEnum,
-	BoolElementResultEnum,
 	BoolExternalResultEnum,
-	DoubleElementResultEnum,
 	DoubleExternalResultEnum,
 	DoubleMatExternalResultEnum,
 	IntExternalResultEnum,
 	JEnum,
-	PatchEnum,
-	PatchNodesEnum,
-	PatchVerticesEnum,
-	PentaP1ElementResultEnum,
 	StringExternalResultEnum,
 	StepEnum,
 	TimeEnum,
-	TriaP1ElementResultEnum,
 	WaterColumnOldEnum,
+	/*}}}*/
+	/*Output Definitions{{{*/
+	OutputdefinitionEnum,
+	OutputdefinitionListEnum,
+	MassfluxatgateEnum,
+	MassfluxatgateNameEnum,
+	MassfluxatgateSegmentsEnum,
 	/*}}}*/
 	/*Responses{{{*/
@@ -547,4 +557,5 @@
 	MaxAbsVzEnum,
 	IceVolumeEnum,
+	IceVolumeAboveFloatationEnum,
 	TotalSmbEnum,
 	/*}}}*/
@@ -560,4 +571,5 @@
 	SubelementMigration2Enum,
 	MaskGroundediceLevelsetEnum,
+	QmuMaskGroundediceLevelsetEnum,
 	/*}}}*/
 	/*Solver{{{*/
@@ -606,6 +618,9 @@
 	DenseEnum,
 	MpiDenseEnum,
+	MpiSparseEnum,
 	SeqEnum,
 	MpiEnum,
+	MumpsEnum,
+	GslEnum,
 	/*}}}*/
 	/*Options{{{*/
@@ -613,8 +628,5 @@
 	GenericOptionEnum,
 	OptionCellEnum,
-	OptionCharEnum,
 	OptionStructEnum,
-	OptionDoubleEnum,
-	OptionLogicalEnum,
 	/*}}}*/
 	/*Rheology law (move too Material) {{{*/
Index: /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 16560)
@@ -37,4 +37,10 @@
 		case AutodiffMassFluxSegmentsPresentEnum : return "AutodiffMassFluxSegmentsPresent";
 		case AutodiffKeepEnum : return "AutodiffKeep";
+		case AutodiffObufsizeEnum : return "AutodiffObufsize";
+		case AutodiffLbufsizeEnum : return "AutodiffLbufsize";
+		case AutodiffCbufsizeEnum : return "AutodiffCbufsize";
+		case AutodiffTbufsizeEnum : return "AutodiffTbufsize";
+		case AutodiffGcTriggerRatioEnum : return "AutodiffGcTriggerRatio";
+		case AutodiffGcTriggerMaxSizeEnum : return "AutodiffGcTriggerMaxSize";
 		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
 		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
@@ -50,11 +56,10 @@
 		case DependentObjectEnum : return "DependentObject";
 		case StressbalanceAbstolEnum : return "StressbalanceAbstol";
-		case StressbalanceIcefrontEnum : return "StressbalanceIcefront";
 		case StressbalanceIsnewtonEnum : return "StressbalanceIsnewton";
 		case StressbalanceMaxiterEnum : return "StressbalanceMaxiter";
-		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
 		case StressbalancePenaltyFactorEnum : return "StressbalancePenaltyFactor";
 		case StressbalanceReferentialEnum : return "StressbalanceReferential";
 		case StressbalanceReltolEnum : return "StressbalanceReltol";
+		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
 		case StressbalanceRequestedOutputsEnum : return "StressbalanceRequestedOutputs";
 		case StressbalanceRestolEnum : return "StressbalanceRestol";
@@ -126,5 +131,4 @@
 		case HydrologyEfficientEnum : return "HydrologyEfficient";
 		case HydrologySedimentKmaxEnum : return "HydrologySedimentKmax";
-		case BasisIntegralEnum : return "BasisIntegral";
 		case WaterTransferEnum : return "WaterTransfer";
 		case IndependentObjectEnum : return "IndependentObject";
@@ -133,5 +137,4 @@
 		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
 		case InversionCostFunctionsEnum : return "InversionCostFunctions";
-		case InversionGradientOnlyEnum : return "InversionGradientOnly";
 		case InversionGradientScalingEnum : return "InversionGradientScaling";
 		case InversionIscontrolEnum : return "InversionIscontrol";
@@ -146,9 +149,9 @@
 		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 MaskIceLevelsetEnum : return "MaskIceLevelset";
+		case QmuMaskIceLevelsetEnum : return "QmuMaskIceLevelset";
 		case MaterialsBetaEnum : return "MaterialsBeta";
 		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
@@ -160,6 +163,21 @@
 		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
 		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
-		case MaterialsRheologyZEnum : return "MaterialsRheologyZ";
-		case MaterialsRheologyZbarEnum : return "MaterialsRheologyZbar";
+		case DamageDEnum : return "DamageD";
+		case QmuDamageDEnum : return "QmuDamageD";
+		case DamageDbarEnum : return "DamageDbar";
+		case DamageLawEnum : return "DamageLaw";
+		case DamageC1Enum : return "DamageC1";
+		case DamageC2Enum : return "DamageC2";
+		case DamageC3Enum : return "DamageC3";
+		case DamageC4Enum : return "DamageC4";
+		case DamageHealingEnum : return "DamageHealing";
+		case DamageStressThresholdEnum : return "DamageStressThreshold";
+		case DamageStabilizationEnum : return "DamageStabilization";
+		case DamagePenaltyThresholdEnum : return "DamagePenaltyThreshold";
+		case DamagePenaltyLockEnum : return "DamagePenaltyLock";
+		case DamagePenaltyFactorEnum : return "DamagePenaltyFactor";
+		case DamageMaxiterEnum : return "DamageMaxiter";
+		case DamageSpcdamageEnum : return "DamageSpcdamage";
+		case DamageMaxDamageEnum : return "DamageMaxDamage";
 		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
 		case MaterialsRhoWaterEnum : return "MaterialsRhoWater";
@@ -173,5 +191,4 @@
 		case MaterialsMantleDensityEnum : return "MaterialsMantleDensity";
 		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
-		case MeshDimensionEnum : return "MeshDimension";
 		case MeshElementonbedEnum : return "MeshElementonbed";
 		case MeshElementonsurfaceEnum : return "MeshElementonsurface";
@@ -190,4 +207,8 @@
 		case MeshYEnum : return "MeshY";
 		case MeshZEnum : return "MeshZ";
+		case MeshTypeEnum : return "MeshType";
+		case Mesh2DhorizontalEnum : return "Mesh2Dhorizontal";
+		case Mesh2DverticalEnum : return "Mesh2Dvertical";
+		case Mesh3DEnum : return "Mesh3D";
 		case MiscellaneousNameEnum : return "MiscellaneousName";
 		case MasstransportHydrostaticAdjustmentEnum : return "MasstransportHydrostaticAdjustment";
@@ -215,5 +236,4 @@
 		case SettingsLowmemEnum : return "SettingsLowmem";
 		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
-		case SettingsResultsAsPatchesEnum : return "SettingsResultsAsPatches";
 		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
 		case SurfaceforcingsDelta18oEnum : return "SurfaceforcingsDelta18o";
@@ -252,4 +272,6 @@
 		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
 		case ThermalStabilizationEnum : return "ThermalStabilization";
+		case ThermalNumRequestedOutputsEnum : return "ThermalNumRequestedOutputs";
+		case ThermalRequestedOutputsEnum : return "ThermalRequestedOutputs";
 		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
 		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
@@ -265,4 +287,5 @@
 		case TransientIsthermalEnum : return "TransientIsthermal";
 		case TransientIsgiaEnum : return "TransientIsgia";
+		case TransientIsdamageEnum : return "TransientIsdamage";
 		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
 		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
@@ -272,7 +295,5 @@
 		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
 		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
-		case AdjointSolutionEnum : return "AdjointSolution";
 		case AnalysisCounterEnum : return "AnalysisCounter";
-		case NoneAnalysisEnum : return "NoneAnalysis";
 		case DefaultAnalysisEnum : return "DefaultAnalysis";
 		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
@@ -282,8 +303,8 @@
 		case BalancevelocityAnalysisEnum : return "BalancevelocityAnalysis";
 		case BalancevelocitySolutionEnum : return "BalancevelocitySolution";
-		case BedSlopeAnalysisEnum : return "BedSlopeAnalysis";
+		case L2ProjectionBaseAnalysisEnum : return "L2ProjectionBaseAnalysis";
 		case BedSlopeSolutionEnum : return "BedSlopeSolution";
-		case BedSlopeXAnalysisEnum : return "BedSlopeXAnalysis";
-		case BedSlopeYAnalysisEnum : return "BedSlopeYAnalysis";
+		case DamageEvolutionSolutionEnum : return "DamageEvolutionSolution";
+		case DamageEvolutionAnalysisEnum : return "DamageEvolutionAnalysis";
 		case StressbalanceAnalysisEnum : return "StressbalanceAnalysis";
 		case StressbalanceSIAAnalysisEnum : return "StressbalanceSIAAnalysis";
@@ -291,5 +312,4 @@
 		case StressbalanceVerticalAnalysisEnum : return "StressbalanceVerticalAnalysis";
 		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
-		case EnthalpySolutionEnum : return "EnthalpySolution";
 		case FlaimAnalysisEnum : return "FlaimAnalysis";
 		case FlaimSolutionEnum : return "FlaimSolution";
@@ -303,9 +323,9 @@
 		case FreeSurfaceBaseAnalysisEnum : return "FreeSurfaceBaseAnalysis";
 		case FreeSurfaceTopAnalysisEnum : return "FreeSurfaceTopAnalysis";
+		case ExtrudeFromBaseAnalysisEnum : return "ExtrudeFromBaseAnalysis";
+		case ExtrudeFromTopAnalysisEnum : return "ExtrudeFromTopAnalysis";
 		case SteadystateSolutionEnum : return "SteadystateSolution";
-		case SurfaceSlopeAnalysisEnum : return "SurfaceSlopeAnalysis";
+		case L2ProjectionTopAnalysisEnum : return "L2ProjectionTopAnalysis";
 		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
-		case SurfaceSlopeXAnalysisEnum : return "SurfaceSlopeXAnalysis";
-		case SurfaceSlopeYAnalysisEnum : return "SurfaceSlopeYAnalysis";
 		case SmoothedSurfaceSlopeXAnalysisEnum : return "SmoothedSurfaceSlopeXAnalysis";
 		case SmoothedSurfaceSlopeYAnalysisEnum : return "SmoothedSurfaceSlopeYAnalysis";
@@ -315,4 +335,6 @@
 		case GiaSolutionEnum : return "GiaSolution";
 		case GiaAnalysisEnum : return "GiaAnalysis";
+		case MeshdeformationSolutionEnum : return "MeshdeformationSolution";
+		case MeshdeformationAnalysisEnum : return "MeshdeformationAnalysis";
 		case ApproximationEnum : return "Approximation";
 		case NoneApproximationEnum : return "NoneApproximation";
@@ -342,5 +364,4 @@
 		case ControlInputEnum : return "ControlInput";
 		case DatasetInputEnum : return "DatasetInput";
-		case DofIndexingEnum : return "DofIndexing";
 		case DoubleInputEnum : return "DoubleInput";
 		case DataSetParamEnum : return "DataSetParam";
@@ -350,19 +371,14 @@
 		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 InputToExtrudeEnum : return "InputToExtrude";
+		case InputToL2ProjectEnum : return "InputToL2Project";
 		case IntParamEnum : return "IntParam";
 		case IntVecParamEnum : return "IntVecParam";
 		case TransientParamEnum : return "TransientParam";
-		case IceFrontTypeEnum : return "IceFrontType";
-		case SSA2dIceFrontEnum : return "SSA2dIceFront";
-		case SSA3dIceFrontEnum : return "SSA3dIceFront";
 		case MaticeEnum : return "Matice";
-		case MatdamageiceEnum : return "Matdamageice";
 		case MatparEnum : return "Matpar";
 		case NodeEnum : return "Node";
@@ -370,6 +386,4 @@
 		case NumericalfluxTypeEnum : return "NumericalfluxType";
 		case ParamEnum : return "Param";
-		case L1L2IceFrontEnum : return "L1L2IceFront";
-		case HOIceFrontEnum : return "HOIceFront";
 		case PengridEnum : return "Pengrid";
 		case PenpairEnum : return "Penpair";
@@ -387,7 +401,8 @@
 		case SpcStaticEnum : return "SpcStatic";
 		case SpcTransientEnum : return "SpcTransient";
-		case FSIceFrontEnum : return "FSIceFront";
 		case StringArrayParamEnum : return "StringArrayParam";
 		case StringParamEnum : return "StringParam";
+		case SegEnum : return "Seg";
+		case SegInputEnum : return "SegInput";
 		case TriaEnum : return "Tria";
 		case TriaInputEnum : return "TriaInput";
@@ -410,5 +425,4 @@
 		case BedSlopeYEnum : return "BedSlopeY";
 		case BoundaryEnum : return "Boundary";
-		case ConstantEnum : return "Constant";
 		case ConvergedEnum : return "Converged";
 		case FillEnum : return "Fill";
@@ -418,8 +432,6 @@
 		case InternalEnum : return "Internal";
 		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";
@@ -447,5 +459,4 @@
 		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
 		case TemperatureEnum : return "Temperature";
-		case TemperatureOldEnum : return "TemperatureOld";
 		case TemperaturePicardEnum : return "TemperaturePicard";
 		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
@@ -471,5 +482,4 @@
 		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
 		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
-		case StepResponsesEnum : return "StepResponses";
 		case IntMatParamEnum : return "IntMatParam";
 		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
@@ -507,20 +517,18 @@
 		case TaylorHoodEnum : return "TaylorHood";
 		case SaveResultsEnum : return "SaveResults";
-		case BoolElementResultEnum : return "BoolElementResult";
 		case BoolExternalResultEnum : return "BoolExternalResult";
-		case DoubleElementResultEnum : return "DoubleElementResult";
 		case DoubleExternalResultEnum : return "DoubleExternalResult";
 		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
 		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 StringExternalResultEnum : return "StringExternalResult";
 		case StepEnum : return "Step";
 		case TimeEnum : return "Time";
-		case TriaP1ElementResultEnum : return "TriaP1ElementResult";
 		case WaterColumnOldEnum : return "WaterColumnOld";
+		case OutputdefinitionEnum : return "Outputdefinition";
+		case OutputdefinitionListEnum : return "OutputdefinitionList";
+		case MassfluxatgateEnum : return "Massfluxatgate";
+		case MassfluxatgateNameEnum : return "MassfluxatgateName";
+		case MassfluxatgateSegmentsEnum : return "MassfluxatgateSegments";
 		case MinVelEnum : return "MinVel";
 		case MaxVelEnum : return "MaxVel";
@@ -535,4 +543,5 @@
 		case MaxAbsVzEnum : return "MaxAbsVz";
 		case IceVolumeEnum : return "IceVolume";
+		case IceVolumeAboveFloatationEnum : return "IceVolumeAboveFloatation";
 		case TotalSmbEnum : return "TotalSmb";
 		case AbsoluteEnum : return "Absolute";
@@ -544,4 +553,5 @@
 		case SubelementMigration2Enum : return "SubelementMigration2";
 		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
+		case QmuMaskGroundediceLevelsetEnum : return "QmuMaskGroundediceLevelset";
 		case FSSolverEnum : return "FSSolver";
 		case AdjointEnum : return "Adjoint";
@@ -580,13 +590,13 @@
 		case DenseEnum : return "Dense";
 		case MpiDenseEnum : return "MpiDense";
+		case MpiSparseEnum : return "MpiSparse";
 		case SeqEnum : return "Seq";
 		case MpiEnum : return "Mpi";
+		case MumpsEnum : return "Mumps";
+		case GslEnum : return "Gsl";
 		case OptionEnum : return "Option";
 		case GenericOptionEnum : return "GenericOption";
 		case OptionCellEnum : return "OptionCell";
-		case OptionCharEnum : return "OptionChar";
 		case OptionStructEnum : return "OptionStruct";
-		case OptionDoubleEnum : return "OptionDouble";
-		case OptionLogicalEnum : return "OptionLogical";
 		case PatersonEnum : return "Paterson";
 		case ArrheniusEnum : return "Arrhenius";
Index: /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 16560)
@@ -12,5 +12,5 @@
 #include "../Exceptions/exceptions.h"
 
-int  StringToEnumx(const char* name){
+int  StringToEnumx(const char* name,bool notfounderror){
 
    int  stage=1;
@@ -37,4 +37,10 @@
 	      else if (strcmp(name,"AutodiffMassFluxSegmentsPresent")==0) return AutodiffMassFluxSegmentsPresentEnum;
 	      else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
+	      else if (strcmp(name,"AutodiffObufsize")==0) return AutodiffObufsizeEnum;
+	      else if (strcmp(name,"AutodiffLbufsize")==0) return AutodiffLbufsizeEnum;
+	      else if (strcmp(name,"AutodiffCbufsize")==0) return AutodiffCbufsizeEnum;
+	      else if (strcmp(name,"AutodiffTbufsize")==0) return AutodiffTbufsizeEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerRatio")==0) return AutodiffGcTriggerRatioEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerMaxSize")==0) return AutodiffGcTriggerMaxSizeEnum;
 	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
 	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
@@ -50,11 +56,10 @@
 	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
 	      else if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
-	      else if (strcmp(name,"StressbalanceIcefront")==0) return StressbalanceIcefrontEnum;
 	      else if (strcmp(name,"StressbalanceIsnewton")==0) return StressbalanceIsnewtonEnum;
 	      else if (strcmp(name,"StressbalanceMaxiter")==0) return StressbalanceMaxiterEnum;
-	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalancePenaltyFactor")==0) return StressbalancePenaltyFactorEnum;
 	      else if (strcmp(name,"StressbalanceReferential")==0) return StressbalanceReferentialEnum;
 	      else if (strcmp(name,"StressbalanceReltol")==0) return StressbalanceReltolEnum;
+	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalanceRequestedOutputs")==0) return StressbalanceRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalanceRestol")==0) return StressbalanceRestolEnum;
@@ -126,5 +131,4 @@
 	      else if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
 	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
-	      else if (strcmp(name,"BasisIntegral")==0) return BasisIntegralEnum;
 	      else if (strcmp(name,"WaterTransfer")==0) return WaterTransferEnum;
 	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
@@ -133,12 +137,11 @@
 	      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 stage=2;
    }
    if(stage==2){
-	      if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
+	      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,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
 	      else if (strcmp(name,"InversionMaxParameters")==0) return InversionMaxParametersEnum;
 	      else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
@@ -149,9 +152,9 @@
 	      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,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
+	      else if (strcmp(name,"QmuMaskIceLevelset")==0) return QmuMaskIceLevelsetEnum;
 	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
 	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
@@ -163,6 +166,21 @@
 	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
 	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
-	      else if (strcmp(name,"MaterialsRheologyZ")==0) return MaterialsRheologyZEnum;
-	      else if (strcmp(name,"MaterialsRheologyZbar")==0) return MaterialsRheologyZbarEnum;
+	      else if (strcmp(name,"DamageD")==0) return DamageDEnum;
+	      else if (strcmp(name,"QmuDamageD")==0) return QmuDamageDEnum;
+	      else if (strcmp(name,"DamageDbar")==0) return DamageDbarEnum;
+	      else if (strcmp(name,"DamageLaw")==0) return DamageLawEnum;
+	      else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
+	      else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
+	      else if (strcmp(name,"DamageC3")==0) return DamageC3Enum;
+	      else if (strcmp(name,"DamageC4")==0) return DamageC4Enum;
+	      else if (strcmp(name,"DamageHealing")==0) return DamageHealingEnum;
+	      else if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
+	      else if (strcmp(name,"DamageStabilization")==0) return DamageStabilizationEnum;
+	      else if (strcmp(name,"DamagePenaltyThreshold")==0) return DamagePenaltyThresholdEnum;
+	      else if (strcmp(name,"DamagePenaltyLock")==0) return DamagePenaltyLockEnum;
+	      else if (strcmp(name,"DamagePenaltyFactor")==0) return DamagePenaltyFactorEnum;
+	      else if (strcmp(name,"DamageMaxiter")==0) return DamageMaxiterEnum;
+	      else if (strcmp(name,"DamageSpcdamage")==0) return DamageSpcdamageEnum;
+	      else if (strcmp(name,"DamageMaxDamage")==0) return DamageMaxDamageEnum;
 	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
 	      else if (strcmp(name,"MaterialsRhoWater")==0) return MaterialsRhoWaterEnum;
@@ -176,5 +194,4 @@
 	      else if (strcmp(name,"MaterialsMantleDensity")==0) return MaterialsMantleDensityEnum;
 	      else if (strcmp(name,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
-	      else if (strcmp(name,"MeshDimension")==0) return MeshDimensionEnum;
 	      else if (strcmp(name,"MeshElementonbed")==0) return MeshElementonbedEnum;
 	      else if (strcmp(name,"MeshElementonsurface")==0) return MeshElementonsurfaceEnum;
@@ -193,4 +210,8 @@
 	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
 	      else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
+	      else if (strcmp(name,"MeshType")==0) return MeshTypeEnum;
+	      else if (strcmp(name,"Mesh2Dhorizontal")==0) return Mesh2DhorizontalEnum;
+	      else if (strcmp(name,"Mesh2Dvertical")==0) return Mesh2DverticalEnum;
+	      else if (strcmp(name,"Mesh3D")==0) return Mesh3DEnum;
 	      else if (strcmp(name,"MiscellaneousName")==0) return MiscellaneousNameEnum;
 	      else if (strcmp(name,"MasstransportHydrostaticAdjustment")==0) return MasstransportHydrostaticAdjustmentEnum;
@@ -218,5 +239,4 @@
 	      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,"SurfaceforcingsDelta18o")==0) return SurfaceforcingsDelta18oEnum;
@@ -240,5 +260,8 @@
 	      else if (strcmp(name,"SurfaceforcingsIspdd")==0) return SurfaceforcingsIspddEnum;
 	      else if (strcmp(name,"SurfaceforcingsDesfac")==0) return SurfaceforcingsDesfacEnum;
-	      else if (strcmp(name,"SurfaceforcingsS0p")==0) return SurfaceforcingsS0pEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"SurfaceforcingsS0p")==0) return SurfaceforcingsS0pEnum;
 	      else if (strcmp(name,"SurfaceforcingsIssmbgradients")==0) return SurfaceforcingsIssmbgradientsEnum;
 	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
@@ -255,4 +278,6 @@
 	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
 	      else if (strcmp(name,"ThermalStabilization")==0) return ThermalStabilizationEnum;
+	      else if (strcmp(name,"ThermalNumRequestedOutputs")==0) return ThermalNumRequestedOutputsEnum;
+	      else if (strcmp(name,"ThermalRequestedOutputs")==0) return ThermalRequestedOutputsEnum;
 	      else if (strcmp(name,"GiaMantleViscosity")==0) return GiaMantleViscosityEnum;
 	      else if (strcmp(name,"GiaLithosphereThickness")==0) return GiaLithosphereThicknessEnum;
@@ -260,8 +285,5 @@
 	      else if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
 	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
+	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
 	      else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
 	      else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
@@ -271,4 +293,5 @@
 	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
 	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
+	      else if (strcmp(name,"TransientIsdamage")==0) return TransientIsdamageEnum;
 	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
 	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
@@ -278,7 +301,5 @@
 	      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,"NoneAnalysis")==0) return NoneAnalysisEnum;
 	      else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
 	      else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
@@ -288,8 +309,8 @@
 	      else if (strcmp(name,"BalancevelocityAnalysis")==0) return BalancevelocityAnalysisEnum;
 	      else if (strcmp(name,"BalancevelocitySolution")==0) return BalancevelocitySolutionEnum;
-	      else if (strcmp(name,"BedSlopeAnalysis")==0) return BedSlopeAnalysisEnum;
+	      else if (strcmp(name,"L2ProjectionBaseAnalysis")==0) return L2ProjectionBaseAnalysisEnum;
 	      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,"DamageEvolutionSolution")==0) return DamageEvolutionSolutionEnum;
+	      else if (strcmp(name,"DamageEvolutionAnalysis")==0) return DamageEvolutionAnalysisEnum;
 	      else if (strcmp(name,"StressbalanceAnalysis")==0) return StressbalanceAnalysisEnum;
 	      else if (strcmp(name,"StressbalanceSIAAnalysis")==0) return StressbalanceSIAAnalysisEnum;
@@ -297,5 +318,4 @@
 	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
 	      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;
@@ -309,9 +329,9 @@
 	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
 	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
+	      else if (strcmp(name,"ExtrudeFromBaseAnalysis")==0) return ExtrudeFromBaseAnalysisEnum;
+	      else if (strcmp(name,"ExtrudeFromTopAnalysis")==0) return ExtrudeFromTopAnalysisEnum;
 	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
-	      else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
+	      else if (strcmp(name,"L2ProjectionTopAnalysis")==0) return L2ProjectionTopAnalysisEnum;
 	      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,"SmoothedSurfaceSlopeXAnalysis")==0) return SmoothedSurfaceSlopeXAnalysisEnum;
 	      else if (strcmp(name,"SmoothedSurfaceSlopeYAnalysis")==0) return SmoothedSurfaceSlopeYAnalysisEnum;
@@ -321,4 +341,6 @@
 	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
 	      else if (strcmp(name,"GiaAnalysis")==0) return GiaAnalysisEnum;
+	      else if (strcmp(name,"MeshdeformationSolution")==0) return MeshdeformationSolutionEnum;
+	      else if (strcmp(name,"MeshdeformationAnalysis")==0) return MeshdeformationAnalysisEnum;
 	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
 	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
@@ -348,5 +370,4 @@
 	      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,"DataSetParam")==0) return DataSetParamEnum;
@@ -356,19 +377,17 @@
 	      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,"InputToExtrude")==0) return InputToExtrudeEnum;
+	      else if (strcmp(name,"InputToL2Project")==0) return InputToL2ProjectEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"IntParam")==0) return IntParamEnum;
 	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
 	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
-	      else if (strcmp(name,"IceFrontType")==0) return IceFrontTypeEnum;
-	      else if (strcmp(name,"SSA2dIceFront")==0) return SSA2dIceFrontEnum;
-	      else if (strcmp(name,"SSA3dIceFront")==0) return SSA3dIceFrontEnum;
 	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
-	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
 	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
 	      else if (strcmp(name,"Node")==0) return NodeEnum;
@@ -376,6 +395,4 @@
 	      else if (strcmp(name,"NumericalfluxType")==0) return NumericalfluxTypeEnum;
 	      else if (strcmp(name,"Param")==0) return ParamEnum;
-	      else if (strcmp(name,"L1L2IceFront")==0) return L1L2IceFrontEnum;
-	      else if (strcmp(name,"HOIceFront")==0) return HOIceFrontEnum;
 	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
 	      else if (strcmp(name,"Penpair")==0) return PenpairEnum;
@@ -383,8 +400,5 @@
 	      else if (strcmp(name,"PentaInput")==0) return PentaInputEnum;
 	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
 	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
 	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
@@ -396,7 +410,8 @@
 	      else if (strcmp(name,"SpcStatic")==0) return SpcStaticEnum;
 	      else if (strcmp(name,"SpcTransient")==0) return SpcTransientEnum;
-	      else if (strcmp(name,"FSIceFront")==0) return FSIceFrontEnum;
 	      else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
 	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
+	      else if (strcmp(name,"Seg")==0) return SegEnum;
+	      else if (strcmp(name,"SegInput")==0) return SegInputEnum;
 	      else if (strcmp(name,"Tria")==0) return TriaEnum;
 	      else if (strcmp(name,"TriaInput")==0) return TriaInputEnum;
@@ -419,5 +434,4 @@
 	      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,"Fill")==0) return FillEnum;
@@ -427,8 +441,6 @@
 	      else if (strcmp(name,"Internal")==0) return InternalEnum;
 	      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;
@@ -456,5 +468,4 @@
 	      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;
@@ -480,5 +491,4 @@
 	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
 	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
-	      else if (strcmp(name,"StepResponses")==0) return StepResponsesEnum;
 	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
 	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
@@ -496,5 +506,8 @@
 	      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 stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"StressTensoryy")==0) return StressTensoryyEnum;
 	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
@@ -506,8 +519,5 @@
 	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
 	      else if (strcmp(name,"P1bubble")==0) return P1bubbleEnum;
-         else stage=5;
-   }
-   if(stage==5){
-	      if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
+	      else if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
 	      else if (strcmp(name,"P2")==0) return P2Enum;
 	      else if (strcmp(name,"P2xP1")==0) return P2xP1Enum;
@@ -519,20 +529,18 @@
 	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
 	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
-	      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,"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,"StringExternalResult")==0) return StringExternalResultEnum;
 	      else if (strcmp(name,"Step")==0) return StepEnum;
 	      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,"Outputdefinition")==0) return OutputdefinitionEnum;
+	      else if (strcmp(name,"OutputdefinitionList")==0) return OutputdefinitionListEnum;
+	      else if (strcmp(name,"Massfluxatgate")==0) return MassfluxatgateEnum;
+	      else if (strcmp(name,"MassfluxatgateName")==0) return MassfluxatgateNameEnum;
+	      else if (strcmp(name,"MassfluxatgateSegments")==0) return MassfluxatgateSegmentsEnum;
 	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
 	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
@@ -547,4 +555,5 @@
 	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
 	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"IceVolumeAboveFloatation")==0) return IceVolumeAboveFloatationEnum;
 	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
 	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
@@ -556,4 +565,5 @@
 	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
 	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
+	      else if (strcmp(name,"QmuMaskGroundediceLevelset")==0) return QmuMaskGroundediceLevelsetEnum;
 	      else if (strcmp(name,"FSSolver")==0) return FSSolverEnum;
 	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
@@ -592,13 +602,13 @@
 	      else if (strcmp(name,"Dense")==0) return DenseEnum;
 	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
+	      else if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
 	      else if (strcmp(name,"Seq")==0) return SeqEnum;
 	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
+	      else if (strcmp(name,"Mumps")==0) return MumpsEnum;
+	      else if (strcmp(name,"Gsl")==0) return GslEnum;
 	      else if (strcmp(name,"Option")==0) return OptionEnum;
 	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
 	      else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
-	      else if (strcmp(name,"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;
@@ -608,4 +618,7 @@
    }
 	/*If we reach this point, the string provided has not been found*/
-	_error_("Enum " << name << " not found");
+	if(notfounderror)
+		_error_("Enum " << name << " not found");
+	else
+		return -1;
 }
Index: /issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 16559)
+++ /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 16560)
@@ -73,5 +73,5 @@
 #include "../Exceptions/exceptions.h"
 
-int  StringToEnumx(const char* name){
+int  StringToEnumx(const char* name,bool notfounderror){
 
    int  stage=1;
@@ -97,8 +97,43 @@
 cat <<END >> $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
 	/*If we reach this point, the string provided has not been found*/
-	_error_("Enum " << name << " not found");
+	if(notfounderror)
+		_error_("Enum " << name << " not found");
+	else
+		return -1;
 }
 END
 #}}}
+##Build EnumToAnalysis.cpp {{{
+##Header
+#cat <<END > $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+#/*
+#* \file EnumToAnalysis.cpp
+#* \brief: output class depending on enum
+#*
+#*   WARNING: DO NOT MODIFY THIS FILE
+#*            this file has been automatically generated by Synchronize.sh
+#*            Please read README for more information
+#*/
+#
+##include "./analyses.h"
+##include "../shared/shared.h"
+#
+#Analysis* EnumToAnalysis(int analysis_enum){
+#
+#	switch(analysis_enum){
+#END
+##core
+#cat temp | grep [a-z]Analysis | \
+#	grep -v DefaultAnalysis | grep -v FlaimAnalysis | grep -v SurfaceSlopeAnalysis | grep -v BedSlopeAnalysis | \
+#	awk '{print "\t\t#ifdef _HAVE_"toupper(substr($1,1,length($1)-12))"_\n\t\t" "case " $1" : return new " substr($1,1,length($1)-4) "();\n\t\t#endif"}' \
+#		>> $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+#
+##Footer
+#cat <<END >> $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+#default : _error_("enum provided not supported ("<<EnumToStringx(analysis_enum)<<")");
+#	}
+#}
+#END
+##}}}
 #Build EnumDefinitions.py{{{
 cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
Index: /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 16560)
@@ -9,49 +9,71 @@
 #endif
 
+#include <cstring>
+#include <cstdio>
 #include "./exceptions.h"
 #include "../io/Print/Print.h"
 #include "../io/Comm/IssmComm.h"
+#include "../MemOps/MemOps.h"
 
-ErrorException::ErrorException(const string &what_arg){/*{{{*/
+ErrorException::ErrorException(const string & what_arg){/*{{{*/
 
-	what_str=what_arg;
-	file_name="";
-	function_name="";
-	file_line=0;
+	int len;
+	len           = strlen(what_arg.c_str())+1;
+	what_str      = new char[len];
+	memcpy(what_str,what_arg.c_str(),len);
+
+	file_name     = NULL;
+	function_name = NULL;
+	file_line     = 0;
+
 }/*}}}*/
 ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
 
-	what_str=what_arg;
-	file_name=what_file;
-	function_name=what_function;
-	file_line=what_line;
+	int len;
+
+	len      = strlen(what_arg.c_str())+1;
+	what_str = new char[len];
+	memcpy(what_str,what_arg.c_str(),len);
+
+	len       = strlen(what_file.c_str())+1;
+	file_name = new char[len];
+	memcpy(file_name,what_file.c_str(),len);
+
+	len           = strlen(what_function.c_str())+1;
+	function_name = new char[len];
+	memcpy(function_name,what_function.c_str(),len);
+
+	file_line= what_line;
+
 }/*}}}*/
 ErrorException::~ErrorException() throw(){/*{{{*/
+	delete [] what_str;
+	delete [] file_name;
+	delete [] function_name;
 }/*}}}*/
 const char* ErrorException::what() const throw(){/*{{{*/
-	return what_str.c_str();
+	return what_str;
 }/*}}}*/
 void ErrorException::Report() const{/*{{{*/
 
-	int my_rank;
-	int num_procs;
+	/*WINDOWS*/
+	if(!function_name || file_line==0){
+		_printf_("Error message: " << what());
+		return;
+	}
 
 	/*recover my_rank and num_procs:*/
-	my_rank=IssmComm::GetRank();
-	num_procs=IssmComm::GetSize();
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
 
-	if (function_name=="" || file_line==0){ //WINDOWS
-		_printf_("Error message: " << what());
+	if(num_procs==1){
+		_printf_("\n??? Error in ==> " << file_name << ":" << file_line << "\n");
+		_printf_(function_name << " error message: " << what() << "\n\n");
 	}
 	else{
-		if(num_procs==1){
-			_printf_("\n??? Error in ==> " << file_name.c_str() << ":" << file_line << "\n");
-			_printf_(function_name.c_str() << " error message: " << what() << "\n\n");
-		}
-		else{
-			_printf_("\n[" << my_rank<< "] ??? Error using ==> " << file_name.c_str() << ":" << file_line << "\n");
-			_printf_(  "[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n\n");
-		}
+		_printf_("\n[" << my_rank<< "] ??? Error using ==> " << file_name << ":" << file_line << "\n");
+		_printf_(  "[" << my_rank << "] " << function_name << " error message: " << what() << "\n\n");
 	}
+
 	return;
 }/*}}}*/
@@ -60,15 +82,19 @@
 	/*Output*/
 	std::ostringstream buffer;
+	char *message = NULL;
 
-	if (this->file_line==0){ //WINDOWS
-		 buffer << " error message: " << (this->what_str).c_str();
+	/*WINDOWS*/
+	if(!function_name || file_line==0){ 
+		buffer << " error message: " << this->what_str;
 	}
 	else{
-		buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
-		buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
+		buffer << "\nError in ==> " << this->file_name << ":" << file_line << "\n";
+		buffer << this->function_name << " error message: " << this->what_str;
 	}
 
-	const string buffer2 = buffer.str();
-	return buffer2.c_str();
+	/*Convert std::ostringstream to std::string and then create char* */
+	std::string buffer2 = buffer.str();
+	message = xNew<char>(strlen(buffer2.c_str())+1); sprintf(message,"%s",buffer2.c_str());
+	return message;
 }/*}}}*/
 const char* ErrorException::PythonReport() const{/*{{{*/
@@ -76,14 +102,18 @@
 	/*Output*/
 	std::ostringstream buffer;
+	char *message = NULL;
 
-	if (this->file_line==0){ //WINDOWS
-		buffer << " error message: " << (this->what_str).c_str();
+	/*WINDOWS*/
+	if(!function_name || file_line==0){ 
+		buffer << " error message: " << this->what_str;
 	}
 	else{
-		buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
-		buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
+		buffer << "\nError in ==> " << this->file_name << ":" << file_line << "\n";
+		buffer << this->function_name << " error message: " << this->what_str;
 	}
 
-	const string buffer2 = buffer.str();
-	return buffer2.c_str();
+	/*Convert std::ostringstream to std::string and then create char* */
+	std::string buffer2 = buffer.str();
+	message = xNew<char>(strlen(buffer2.c_str())+1); sprintf(message,"%s",buffer2.c_str());
+	return message;
 }/*}}}*/
Index: /issm/trunk/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 16560)
@@ -76,12 +76,12 @@
 class ErrorException: public exception { /*{{{*/
 
-	string   what_str;
-	string   function_name;
-	string   file_name;
-	int      file_line;
+	char* what_str;
+	char* function_name;
+	char* file_name;
+	int   file_line;
 
 	public:
 	ErrorException(const string &what_arg); //for windows
-	ErrorException(const string&  what_file,const string& what_function,int what_line,const string& what_arg);//UNIX
+	ErrorException(const string &what_file,const string& what_function,int what_line,const string& what_arg);//UNIX
 	~ErrorException() throw();
 	virtual const char *what() const throw();
@@ -92,6 +92,3 @@
 };
 /*}}}*/
-
-char* exprintf(const char* format,...);
-
 #endif
Index: sm/trunk/src/c/shared/Exceptions/exprintf.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exprintf.cpp	(revision 16559)
+++ 	(revision )
@@ -1,48 +1,0 @@
-/*!\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 "../MemOps/MemOps.h"
-
-char* exprintf(const char* format,...){
-
-	/*returned string: */
-	char *buffer = NULL;
-	int   n,size = 100;
-
-	//variable list of arguments
-	va_list args;
-
-	while(true){
-
-		/*allocate buffer for given string size*/
-		buffer=xNew<char>(size);
-
-		/* Try to print in the allocated space. */
-		va_start(args, format);
-#ifndef WIN32
-		n=vsnprintf(buffer,size,format,args);
-#else
-		n=vsnprintf(buffer,size,format,args);
-#endif
-		va_end(args);
-
-		/* If that worked, return the string. */
-		if(n>-1 && n<size) break;
-
-		/* Else try again with more space. */
-		if(n>-1)   /* glibc 2.1 */
-		 size=n+1; /* precisely what is needed */
-		else       /* glibc 2.0 */
-		 size*=2;  /* twice the old size */
-
-		xDelete<char>(buffer);
-	}
-
-	return buffer;
-}
Index: /issm/trunk/src/c/shared/Exp/exp.h
===================================================================
--- /issm/trunk/src/c/shared/Exp/exp.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Exp/exp.h	(revision 16560)
@@ -92,5 +92,5 @@
 		//# Points Count Value
 		if(fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy)!=4) _error_("Could not read " << domainname);
-		if(fscanf(fid,"%20u %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
+		if(fscanf(fid,"%20i %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
 		//# X pos Y pos
 		if(fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy)!=5) _error_("Could not read " << domainname);
@@ -130,5 +130,5 @@
 
 		/*Get number of profile vertices: */
-		if(fscanf(fid,"%20u %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
+		if(fscanf(fid,"%20i %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
 
 		/*Skip next line: */
Index: /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 16560)
@@ -46,5 +46,5 @@
 	int     i,iret=0;
 	double  delta,slat;
-	double  cde,re,ex2,ex;
+	double  re,ex2,ex;
 	double  latitude,longitude;
 	double  T,rho,sl,tc,mc;
@@ -55,6 +55,4 @@
 	slat  = standard_parallel;
 
-	/*  Conversion constant from degrees to radians  */
-	cde = 57.29577951;
 	/*  Radius of the earth in meters  */
 	re  = 6378.273*1.e3;
Index: /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 16560)
@@ -48,5 +48,5 @@
 	int     i,iret=0;
 	double  delta,slat;
-	double  cde,re,ex2,ex;
+	double  re,ex2,ex;
 	double  sl,rho,cm,T,chi;
 
@@ -56,6 +56,4 @@
 	slat  = standard_parallel;
 
-	/*  Conversion constant from degrees to radians  */
-	cde  = 57.29577951;
 	/*  Radius of the earth in meters  */
 	re   = 6378.273e+3;
Index: /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 16560)
@@ -367,20 +367,2 @@
 
 }/*}}}*/
-/*FUNCTION MatrixTranspose(IssmDouble* Adet,IssmDouble* A) {{{*/
-void MatrixTranspose(IssmDouble* tA,IssmDouble* 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/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 16559)
+++ /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 16560)
@@ -15,5 +15,4 @@
 void Matrix3x3Invert(IssmDouble* Ainv, IssmDouble* A);
 void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A);
-void MatrixTranspose(IssmDouble* tA,IssmDouble* A,int nrows, int ncols);
 
 #endif //ifndef _MATRIXUTILS_H_
Index: /issm/trunk/src/c/shared/MemOps/MemOps.cpp
===================================================================
--- /issm/trunk/src/c/shared/MemOps/MemOps.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/MemOps/MemOps.cpp	(revision 16560)
@@ -5,5 +5,4 @@
  *      Author: utke
  */
-
 
 #ifdef HAVE_CONFIG_H
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 16560)
@@ -45,15 +45,9 @@
 	static IssmPDouble* xip [MAX_LINE_GAUS_PTS]={xi1  ,xi2  ,xi3  ,xi4  };
 
-	static int np[MAX_LINE_GAUS_PTS]={sizeof(wgt1 )/sizeof(IssmPDouble),
-		sizeof(wgt2 )/sizeof(IssmPDouble),
-		sizeof(wgt3 )/sizeof(IssmPDouble),
-		sizeof(wgt4 )/sizeof(IssmPDouble)};
-
-	//	_printf0_("Gauss-Legendre recurrence coefficients ngaus=" << ngaus << "\n");
 	*pxgaus =xNew<IssmPDouble>(ngaus);
 	*pxwgt  =xNew<IssmPDouble>(ngaus);
 
 	/*  check to see if Gauss points need to be calculated  */
-	if (ngaus <= MAX_LINE_GAUS_PTS) {
+	if(ngaus <= MAX_LINE_GAUS_PTS) {
 
 		/*  copy the points from the static arrays (noting that the pointers
@@ -61,10 +55,10 @@
 			 have to know to not free them)  */
 
-		for (i=0; i<ngaus; i++) {
+		for(i=0; i<ngaus; i++) {
 			(*pxgaus)[i]=xip [ngaus-1][i];
 			(*pxwgt )[i]=wgtp[ngaus-1][i];
 		}
 	}
-	else {
+	else{
 
 		/*  calculate the Gauss points using recurrence relations  */
@@ -1259,7 +1253,4 @@
 		0.250000000000000, 0.500000000000000, 0.166666666666667, 
 		0.166666666666667, 0.166666666666667};
-	static IssmPDouble l23[]={
-		0.250000000000000, 0.166666666666667, 0.500000000000000, 
-		0.166666666666667, 0.166666666666667};
 	static IssmPDouble l33[]={
 		0.250000000000000, 0.166666666666667, 0.166666666666667, 
@@ -1511,11 +1502,4 @@
 	static IssmPDouble* xip [MAX_LINE_GLOB_PTS]={xi1  ,xi2  ,xi3  ,xi4  ,xi5  };
 
-	static int np[MAX_LINE_GLOB_PTS]={sizeof(wgt1 )/sizeof(IssmPDouble),
-		sizeof(wgt2 )/sizeof(IssmPDouble),
-		sizeof(wgt3 )/sizeof(IssmPDouble),
-		sizeof(wgt4 )/sizeof(IssmPDouble),
-		sizeof(wgt5 )/sizeof(IssmPDouble)};
-
-	//	_printf0_("Gauss-Lobatto recurrence coefficients ngaus=" << ngaus << "\n");
 	*pxgaus =xNew<IssmPDouble>(ngaus);
 	*pxwgt  =xNew<IssmPDouble>(ngaus);
Index: /issm/trunk/src/c/shared/String/sharedstring.h
===================================================================
--- /issm/trunk/src/c/shared/String/sharedstring.h	(revision 16559)
+++ /issm/trunk/src/c/shared/String/sharedstring.h	(revision 16560)
@@ -7,9 +7,4 @@
 
 int  DescriptorIndex(char* root, int* pindex,char* descriptor);
-
-#ifndef WIN32
-int stricmp(const char* a,const char* b);
-#endif
-
 void ApiPrintf(const char* string);
 
Index: sm/trunk/src/c/shared/String/stricmp.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/stricmp.cpp	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-/* \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/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 16559)
+++ /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 16560)
@@ -109,5 +109,5 @@
 	int i;
 	for (i=0;i<nriftsegs;i++){
-		if ((*(riftsegments+4*i+0)==el) | (*(riftsegments+4*i+1)==el)){
+		if ((*(riftsegments+4*i+0)==el) || (*(riftsegments+4*i+1)==el)){
 			return 1;
 		}
@@ -474,6 +474,6 @@
 				node3=segments[3*k+0]-1; node4=segments[3*k+1]-1;
 				/*We are trying to find 2 elements, where position of node3 == position of node1, and position of node4 == position of node2*/
-				if (   (x[node3]==x[node1]) && (y[node3]==y[node1]) && (x[node4]==x[node2]) && (y[node4]==y[node2])
-				    || (x[node3]==x[node2]) && (y[node3]==y[node2]) && (x[node4]==x[node1]) && (y[node4]==y[node1])  ){
+				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];
@@ -488,178 +488,4 @@
 	*priftsnumpairs=riftsnumpairs;
 	*priftspairs=riftspairs;
-	return noerr;
-}/*}}}*/
-/*FUNCTION RemoveRifts{{{*/
-int RemoveRifts(int** pindex,double** px,double** py,int* pnods,int** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,int** rifts1segments,int** rifts1pairs,int nel){
-
-	int noerr=1;
-	int i,j,k,counter,counter1,counter2;
-
-	/*intermediary: */
-	int    *riftsegments = NULL;
-	int    *riftpairs    = NULL;
-	int     node1,node2,node3,node4,temp_node;
-	int     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: */
-	int    *index    = *pindex;
-	double *x        = *px;
-	double *y        = *py;
-	int     nods     = *pnods;     ;
-	int    *segments = *psegments;
-	int     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-fabs(xmin); 
-	ymin=ymin-fabs(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=xNew<int>(max_size);
-	mergingnodes=xNew<int>(max_size);
-
-	/*Go through the rifts segments, and identify which node we are going to merge with its counterpart on the other side 
-	 *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=*(riftsegments+3*k+0);
-					node4=*(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=xReNew<double>(x,nods,newnods);
-	yreal=xReNew<double>(y,nods,newnods);
-	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++;
-		}
-	}
-	xDelete<double>(x); x=xreal;
-	xDelete<double>(y); y=yreal;
-
-	/*Assign output pointers:*/
-	*pindex=index;
-	*px=x;
-	*py=y;
-	*pnods=newnods;
-	*psegments=segments;
-	*pnumsegs=numsegs;
 	return noerr;
 }/*}}}*/
Index: /issm/trunk/src/c/shared/TriMesh/trimesh.h
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/trimesh.h	(revision 16559)
+++ /issm/trunk/src/c/shared/TriMesh/trimesh.h	(revision 16560)
@@ -23,5 +23,4 @@
 int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel);
 int FindElement(double A,double B,int* index,int nel);
-int RemoveRifts(int** pindex,double** px,double** py,int* pnods,int** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,int** rifts1segments,double** rifts1pairs,int nel);
 int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs);
 int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nels);
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_damage_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_damage_nonlinear.cpp	(revision 16560)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_damage_nonlinear.cpp	(revision 16560)
@@ -0,0 +1,80 @@
+/*
+ * \brief: solutionsequence_damage_nonlinear.cpp: core of the damage solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_damage_nonlinear(FemModel* femmodel){
+
+	/*solution : */
+	Vector<IssmDouble>* Dg=NULL; 
+	Vector<IssmDouble>* Df=NULL; 
+	Vector<IssmDouble>* Df_old=NULL; 
+	Vector<IssmDouble>* ys=NULL; 
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
+
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+	int damage_penalty_threshold;
+	int damage_maxiter;
+
+	/*parameters:*/
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&damage_penalty_threshold,DamagePenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&damage_maxiter,DamageMaxiterEnum);
+
+	count=1;
+	converged=false;
+
+	InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+	InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
+	femmodel->UpdateConstraintsx();
+
+	for(;;){
+
+		delete Df_old; Df_old=Df;
+		SystemMatricesx(&Kff, &Kfs, &pf,&df, NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&Df, Kff, pf,Df_old, df, femmodel->parameters);
+		delete Kff;delete pf;delete Dg; delete df;
+		Mergesolutionfromftogx(&Dg, Df,ys,femmodel->nodes,femmodel->parameters); delete ys;
+		InputUpdateFromSolutionx(femmodel,Dg);
+
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+
+		if (!converged){
+			if(VerboseConvergence()) _printf0_("   #unstable constraints = " << num_unstable_constraints << "\n");
+			if (num_unstable_constraints <= damage_penalty_threshold)converged=true;
+			if (count>=damage_maxiter){
+				converged=true;
+				_printf0_("   maximum number of iterations (" << damage_maxiter << ") exceeded\n"); 
+			}
+		}
+		count++;
+
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+
+		if(converged)break;
+	}
+
+	InputUpdateFromSolutionx(femmodel,Dg);
+
+	/*Free ressources: */
+	delete Dg;
+	delete Df;
+	delete Df_old;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 16559)
+++ /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 16560)
@@ -13,4 +13,5 @@
 
 void solutionsequence_thermal_nonlinear(FemModel* femmodel);
+void solutionsequence_damage_nonlinear(FemModel* femmodel);
 void solutionsequence_hydro_nonlinear(FemModel* femmodel);
 void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
Index: /issm/trunk/src/c/toolkits/issm/Bucket.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 16560)
@@ -131,9 +131,7 @@
 		void SpawnBucketsPerCpu(DataSet* bucketsofcpu_i,int rank_i,int* rowranks){ /*{{{*/
 
-			int i,j;
-
 			/*go through our idxm index of rows this bucket owns, and spawn buckets  
 			 *if these rows belong to cpu rank_i. Use rowranks to determine this.*/
-			for(i=0;i<m;i++){
+			for(int i=0;i<m;i++){
 				if (rowranks[idxm[i]]==rank_i){
 					/*This row belongs to cpu rank_i, so spawn a bucket with this row, and add it to the bucketsofcpu_i dataset: */
@@ -147,6 +145,5 @@
 			}
 
-		};
-		/*}}}*/
+		}; /*}}}*/
 		int BucketType(void){ /*{{{*/
 
Index: /issm/trunk/src/c/toolkits/issm/IssmMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMat.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/IssmMat.h	(revision 16560)
@@ -29,4 +29,5 @@
 template <class doubletype> class IssmDenseMat;
 template <class doubletype> class IssmMpiDenseMat;
+template <class doubletype> class IssmMpiSparseMat;
 class Parameters;
 
@@ -53,4 +54,11 @@
 					#endif
 					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>();
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
 				default:
 					_error_("matrix type not supported yet!");
@@ -72,4 +80,11 @@
 					#endif
 					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
 				default:
 					_error_("matrix type not supported yet!");
@@ -91,4 +106,11 @@
 					#endif
 					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N,sparsity);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
 				default:
 					_error_("matrix type not supported yet!");
@@ -110,4 +132,11 @@
 					#endif
 					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
 				default:
 					_error_("matrix type not supported yet!");
@@ -129,4 +158,11 @@
 					#endif
 					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(serial_mat,M,N,sparsity);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
 				default:
 					_error_("matrix type not supported yet!");
@@ -147,4 +183,11 @@
 					#else
 					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
 					#endif
 					break;
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 16560)
@@ -146,7 +146,7 @@
 					_printf_("cpu " << i << " #rows: " << this->m << "\n");
 					for (j=0;j<this->m;j++){
-						_printf_("row " << j << "\n");
+						_printf_("row " << j << ":");
 						for (k=0;k<this->N;k++){
-							_printf_(this->matrix[j*this->N+k] << " \n");
+							if(this->matrix[j*this->N+k]!=0)_printf_("(" << k << "," << this->matrix[j*this->N+k] << ") ");
 						}
 						_printf_("\n");
@@ -504,6 +504,4 @@
 		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
 
-			int i;
-
 			/*output: */
 			IssmMpiVec<IssmDouble>* uf=NULL;
@@ -513,14 +511,32 @@
 			pf=(IssmMpiVec<IssmDouble>*)pfin;
 
-			/*Initialize output: */
-			uf=pf->Duplicate();
-
-			/*Let's try and use the MUMPS solver here: */
-			#ifdef _HAVE_MUMPS_
-			MpiDenseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
-			#else
-			_error_("IssmMpiDenseMat solver requires MUMPS solver");
-			#endif
-			return (IssmAbsVec<IssmDouble>*)uf;
+			switch(IssmSolverTypeFromToolkitOptions()){
+				case MumpsEnum: {
+					/*Initialize output: */
+					uf=pf->Duplicate();
+					#ifdef _HAVE_MUMPS_
+					MpiDenseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
+					#else
+					_error_("IssmMpiDenseMat solver requires MUMPS solver");
+					#endif
+					return (IssmAbsVec<IssmDouble>*)uf;
+									 }
+				case GslEnum: {
+
+					IssmDouble* x=NULL;
+					#ifdef _HAVE_GSL_
+
+					DenseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+					uf=new IssmMpiVec<IssmDouble>(x,this->N); xDelete(x);
+
+					return (IssmAbsVec<IssmDouble>*)uf;
+					#else
+					_error_("GSL support not compiled in!");
+					#endif
+								  }
+				default:
+					_error_("solver type not supported yet!");
+			}
 
 		}/*}}}*/
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 16560)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 16560)
@@ -0,0 +1,598 @@
+/*!\file:  IssmMpiSparseMat.h
+ * \brief implementation of parallel sparse ISSM matrix. Internally, the parallel sparse matrix is 
+ * split in rows across each cpu. Locally, on each cpu, the local matrix is represented by a vector of sparse rows.
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_MPI_SPARSE_MAT_H_
+#define _ISSM_MPI_SPARSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+#include "../mumps/mumpsincludes.h"
+#include "./Bucket.h"
+#include "./IssmMpiVec.h"
+#include "./SparseRow.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsMat;
+
+template <class doubletype> 
+class IssmMpiSparseMat:public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N;  //global size
+		int m;    //local number of rows
+		SparseRow<doubletype>** matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global matrix.*/
+		/*IssmMpiSparseMat constructors, destructors*/
+		/*FUNCTION IssmMpiSparseMat(){{{*/
+		IssmMpiSparseMat(){
+			this->M=0;
+			this->N=0;
+			this->m=0;
+			this->matrix=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiSparseMat(int M,int N){{{*/
+		IssmMpiSparseMat(int Min,int Nin){
+			this->Init(Min,Nin);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiSparseMat(int M,int N, doubletype sparsity){{{*/
+		IssmMpiSparseMat(int pM,int pN, doubletype sparsity){
+			/*no sparsity involved here, the sparsity pattern is resolve during the assemble phase: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiSparseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		IssmMpiSparseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){
+
+			int i;
+
+			/*no sparsity involved here, the sparsity pattern is resolved at the assemble phase: */
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+			this->m=min;
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N){
+				this->matrix=xNew<SparseRow<doubletype>*>(m);
+				for(i=0;i<m;i++){
+					this->matrix[i]=new SparseRow<doubletype>(N);
+				}
+			}
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiSparseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+		IssmMpiSparseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+			/*this is not needed, sparsity pattern is resolved at assemble phase: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiSparseMat::Init(int Min,int Nin){{{*/
+		void Init(int Min,int Nin){
+			
+			int i;
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+
+			/*Figure out local number of rows: */
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N){
+				this->matrix=xNew<SparseRow<doubletype>*>(m);
+				for(i=0;i<m;i++){
+					this->matrix[i]=new SparseRow<doubletype>(N);
+				}
+			}
+		}
+		/*}}}*/
+		/*FUNCTION ~IssmMpiSparseMat(){{{*/
+		~IssmMpiSparseMat(){
+			int i;
+
+			if(m*N){
+				for(i=0;i<m;i++){
+					delete this->matrix[i];
+				}
+				xDelete<SparseRow<doubletype>*>(this->matrix);
+			}
+			M=0;
+			N=0;
+			m=0;
+			delete this->buckets;
+		}
+		/*}}}*/
+
+		/*IssmMpiSparseMat specific routines */
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int my_rank;
+			int i,j,k;
+
+			/*Do a synchronized dump across all the rows: */
+			my_rank=IssmComm::GetRank();
+			for(i=0;i<IssmComm::GetSize();i++){
+				if (my_rank==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for (j=0;j<this->m;j++){
+						_printf_("row " << j << ":");
+						this->matrix[j]->Echo();
+						_printf_("\n");
+					}
+				}
+				ISSM_MPI_Barrier(IssmComm::GetComm());
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(){
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			int           this_row_numvalues;
+			int*          this_row_cols       = NULL;
+			int*          this_row_mods       = NULL;
+			doubletype*   this_row_values     = NULL;
+			int*          numvalues_perrow    = NULL;
+			int           row;
+			
+			doubletype**  values_perrow       = NULL;
+			int**         cols_perrow         = NULL;
+			int**         mods_perrow         = NULL;
+			int*          counters_perrow     = NULL;
+			int           counter;
+
+			/*Early exit: */
+			if(this->M*this->N==0)return; //no need to assemble.
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
+
+			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&col_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			numvalues_fromcpu   = xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			col_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					col_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					col_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*Scatter values around: {{{*/
+			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( col_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, col_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+			}
+			/*}}}*/
+
+			/*Plug values into global matrix. To do so, we are going to first figure out how many overall values each sparse row is going to get, then we fill up these values, and give it to each sparse row: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+
+			/*Figure out how many values each row is going to get: */
+			numvalues_perrow=xNewZeroInit<int>(this->m);
+			for(i=0;i<num_procs;i++){ 
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				for(j=0;j<numvalues;j++)numvalues_perrow[rows[j]-lower_row]++;
+			}
+
+			/*Allocate all the values, cols and mods from each cpu: */
+			values_perrow=xNew<doubletype*>(this->m);
+			cols_perrow=xNew<int*>(this->m);
+			mods_perrow=xNew<int*>(this->m);
+			counters_perrow=xNewZeroInit<int>(this->m);
+
+			for(i=0;i<this->m;i++){
+				values_perrow[i]=xNewZeroInit<doubletype>(numvalues_perrow[i]);
+				cols_perrow[i]=xNewZeroInit<int>(numvalues_perrow[i]);
+				mods_perrow[i]=xNewZeroInit<int>(numvalues_perrow[i]);
+			}
+
+			/*collect:*/
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					row=rows[j]-lower_row;
+					counter=counters_perrow[row];
+					values_perrow[row][counter]=values[j];
+					cols_perrow[row][counter]=cols[j];
+					mods_perrow[row][counter]=mods[j];
+					counter=counters_perrow[row]++;
+				}
+			}
+					
+			/*Plug into matrix: */
+			for(i=0;i<this->m;i++){
+				this->matrix[i]->SetValues(numvalues_perrow[i],cols_perrow[i],values_perrow[i],mods_perrow[i]);
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(numvalues_perrow);
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(col_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(cols);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(col_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			
+			for(i=0;i<this->m;i++){
+				doubletype* values=values_perrow[i]; xDelete<doubletype>(values);
+				int* cols=cols_perrow[i]; xDelete<int>(cols);
+				int* mods=mods_perrow[i]; xDelete<int>(mods);
+			}
+			xDelete<int>(counters_perrow);
+			xDelete<doubletype*>(values_perrow);
+			xDelete<int*>(cols_perrow);
+			xDelete<int*>(mods_perrow);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm,local_norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						local_norm=max(local_norm,this->matrix[i]->Norm(mode));
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return norm;
+					break; 
+				case NORM_FROB:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						local_norm+=this->matrix[i]->Norm(mode);
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+			*pM=M;
+			*pN=N;
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+			*pM=m;
+			*pN=N;
+		}
+		/*}}}*/
+		/*FUNCTION MatMult{{{*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+
+			int         i,j;
+			doubletype *X_serial  = NULL;
+
+			/*A check on the types: */
+			if(IssmVecTypeFromToolkitOptions()!=MpiEnum)_error_("MatMult operation only possible with 'mpi' vectors");
+
+			/*Now that we are sure, cast vectors: */
+			IssmMpiVec<doubletype>* X=(IssmMpiVec<doubletype>*)Xin;
+			IssmMpiVec<doubletype>* AX=(IssmMpiVec<doubletype>*)AXin;
+
+			/*Serialize input Xin: */
+			X_serial=X->ToMPISerial();
+
+			/*Every cpu has a serial version of the input vector. Use it to do the Matrix-Vector multiply 
+			 *locally and plug it into AXin: */
+			for(i=0;i<this->m;i++){
+				AX->vector[i]=this->matrix[i]->Mult(X_serial);
+			}
+
+			/*Free ressources: */
+			xDelete<doubletype>(X_serial);
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		IssmMpiSparseMat<doubletype>* Duplicate(void){
+
+			_error_("not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION ToSerial{{{*/
+		doubletype* ToSerial(void){
+			_error_("not supported yet!");
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the matrix on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(min,idxm,nin,idxn,values,mode));
+
+		}
+		/*}}}*/
+		/*FUNCTION Convert{{{*/
+		void Convert(MatrixType type){
+			_error_("not supported yet!");
+		}
+		/*}}}*/		
+		/*FUNCTION BucketsBuildScatterBuffers{{{*/
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			int        *temp_col_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			int        *col_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			col_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_col_indices_forcpu=col_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_col_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_col_indices_forcpu!=col_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pcol_indices_forcpu = col_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			/*output: */
+			IssmMpiVec<IssmDouble>* uf=NULL;
+			IssmMpiVec<IssmDouble>* pf=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmMpiVec<IssmDouble>*)pfin;
+
+			switch(IssmSolverTypeFromToolkitOptions()){
+				case MumpsEnum: {
+					/*Initialize output: */
+					uf=pf->Duplicate();
+					#ifdef _HAVE_MUMPS_
+					MpiSparseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
+					#else
+					_error_("IssmMpiSparseMat solver requires MUMPS solver");
+					#endif
+					return (IssmAbsVec<IssmDouble>*)uf;
+									 }
+				case GslEnum: {
+
+					IssmDouble* x=NULL;
+					#ifdef _HAVE_GSL_
+
+					_error_("not implemented yet!");
+					//SparseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+					uf=new IssmMpiVec<IssmDouble>(x,this->N); xDelete(x);
+
+					return (IssmAbsVec<IssmDouble>*)uf;
+					#else
+					_error_("GSL support not compiled in!");
+					#endif
+								  }
+				default:
+					_error_("solver type not supported yet!");
+			}
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_MPI_SPARSE_MAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 16560)
@@ -149,5 +149,4 @@
 
 			int        *row_indices_forcpu = NULL;
-			int        *col_indices_forcpu = NULL;
 			int        *modes_forcpu       = NULL;
 			doubletype *values_forcpu      = NULL;
Index: /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 16560)
@@ -36,6 +36,12 @@
 	mat_type=ToolkitOptions::GetToolkitOptionValue("mat_type");
 
-	if ((strcmp(mat_type,"mpidense")==0) || (strcmp(mat_type,"dense")==0)){
-		if (isparallel) mat_type_enum=MpiDenseEnum;
+	if (strcmp(mat_type,"mpidense")==0){
+		mat_type_enum=MpiDenseEnum;
+	}
+	else if (strcmp(mat_type,"mpisparse")==0){
+		mat_type_enum=MpiSparseEnum;
+	}
+	else if (strcmp(mat_type,"dense")==0){
+		if (isparallel) _error_("Dense matrix type not supported for parallel runs with num_procs>1");
 		else mat_type_enum=DenseEnum;
 	}
@@ -63,6 +69,9 @@
 	vec_type=ToolkitOptions::GetToolkitOptionValue("vec_type");
 
-	if ((strcmp(vec_type,"mpi")==0) || (strcmp(vec_type,"seq")==0)){
-		if (isparallel) vec_type_enum=MpiEnum;
+	if (strcmp(vec_type,"mpi")==0){
+		vec_type_enum=MpiEnum;
+	}
+	else if (strcmp(vec_type,"seq")==0){
+		if (isparallel) _error_("Dense vector type not supported for parallel runs with num_procs>1");
 		else vec_type_enum=SeqEnum;
 	}
@@ -75,2 +84,32 @@
 	return vec_type_enum;
 } /*}}}*/  
+int IssmSolverTypeFromToolkitOptions(void){ /*{{{*/
+
+	char* solver_type=NULL;
+	int   solver_type_enum;
+	int   num_procs=0;
+	bool  isparallel=false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve solver type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc vector types: */
+	solver_type=ToolkitOptions::GetToolkitOptionValue("solver_type");
+
+	if (strcmp(solver_type,"mumps")==0){
+		solver_type_enum=MumpsEnum;
+	}
+	else if (strcmp(solver_type,"gsl")==0){
+		if (isparallel) _error_("Gsl solver type not supported for parallel runs with num_procs>1");
+		else solver_type_enum=GslEnum;
+	}
+	else _error_("solver type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(solver_type);
+
+	/*return: */
+	return solver_type_enum;
+} /*}}}*/  
Index: /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 16560)
@@ -18,4 +18,5 @@
 int IssmMatTypeFromToolkitOptions(void);
 int IssmVecTypeFromToolkitOptions(void);
+int IssmSolverTypeFromToolkitOptions(void);
 
 #endif //#ifndef _ISSMMAT_H_
Index: /issm/trunk/src/c/toolkits/issm/SparseRow.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SparseRow.h	(revision 16560)
+++ /issm/trunk/src/c/toolkits/issm/SparseRow.h	(revision 16560)
@@ -0,0 +1,154 @@
+/*!\file:  SparseRow: 
+ * \brief implementation of a sparse row, which can then be used to make a sparse matrix.
+ */ 
+
+#ifndef _SPARSE_ROW_H_
+#define _SPARSE_ROW_H_
+
+/*Headers:*/
+#include "../toolkitsenums.h"
+#include "../../shared/shared.h"
+
+template <class doubletype> 
+class SparseRow{
+
+	public:
+
+		int         M; //real size
+		int         ncols; //number of non-zeros 
+		int*        indices;
+		doubletype* values;
+		
+		/*SparseRow constructors, destructors*/
+		SparseRow(){ /*{{{*/
+			 M=0;
+			 ncols=0;
+			 indices=NULL;
+			 values=NULL;
+		} /*}}}*/
+		SparseRow(int in_M){/*{{{*/
+			
+			M=in_M;
+			ncols=0;
+			indices=NULL;
+			values=NULL;
+
+		} /*}}}*/
+		~SparseRow(){/*{{{*/
+			if(ncols){
+				xDelete<int>(indices);
+				xDelete<doubletype>(values);
+			}
+		} /*}}}*/
+
+		/*SparseRow specific routines*/
+		void Echo(){ /*{{{*/
+			int i;
+
+			for(i=0;i<ncols;i++){
+				_printf_("(" << indices[i] << "," << values[i] << ") ");
+			}
+		} /*}}}*/
+		void SetValues(int numvalues,int* cols,doubletype* vals, int* mods){ /*{{{*/
+
+			int count;
+			int i,j;
+
+			if(!M)_error_("unknow dimension for this sparse row!");
+
+			/*Deallocate if already allocated: */
+			if(ncols){
+				xDelete<int>(indices);
+				xDelete<doubletype>(values);
+			}
+
+			/*check numvalues: */
+			if(!numvalues)return;
+
+			/*Go through cols and resolve duplicates: */
+			for(i=0;i<numvalues;i++){
+				for(j=i+1;j<numvalues;j++){
+					if (cols[j]==cols[i]){
+						if (mods[j]==ADD_VAL){
+							vals[i]+=vals[j];
+						}
+						else vals[i]=vals[j];
+						cols[j]=-1;
+					}
+					/*Ensure that this value will not be used anymore: */
+				}
+			}
+
+			/*Now go through cols once more, and retrieve only what we need: */
+			ncols=0;
+			for(i=0;i<numvalues;i++)if(cols[i]>=0)ncols++;
+
+			/*Allocate and fill: */
+			indices=xNew<int>(ncols); _assert_(indices);
+			values=xNewZeroInit<doubletype>(ncols);  _assert_(values);
+			
+			count=0;
+			for(i=0;i<numvalues;i++){
+				if(cols[i]>=0){
+					indices[count]=cols[i];
+					values[count]=vals[i];
+					count++;
+				}
+			}
+		
+			if(count!=ncols)_error_("counter problem during set values operations");
+		} /*}}}*/
+		doubletype Norm(NormMode mode){ /*{{{*/
+
+			int i;
+			doubletype norm=0;
+
+			switch(mode){
+				case NORM_INF:
+					for(i=0;i<ncols;i++){
+						norm+=fabs(values[i]);
+					}
+					return norm;
+					break; 
+				case NORM_FROB:
+					for(i=0;i<ncols;i++){
+						norm+=pow(values[i],2);
+					}
+					return norm;
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		doubletype Mult(doubletype* X){ /*{{{*/
+
+			int i;
+			doubletype mult=0;
+
+			for(i=0;i<ncols;i++){
+				mult+=values[i]*X[indices[i]];
+			}
+			
+			return mult;
+		}
+		/*}}}*/
+		int Nnz(void){ /*{{{*/
+
+			return ncols;
+		}
+		/*}}}*/
+		void SetIrnJcnA(int* irn_loc,int* jcn_loc,doubletype* a_loc,int i_index,int count){/*{{{*/
+			int i;
+
+			for(i=0;i<ncols;i++){
+				irn_loc[count+i]=i_index;
+				jcn_loc[count+i]=indices[i]+1; //fortran indexing
+				a_loc[count+i]=values[i];
+			}
+		}
+		/*}}}*/
+};
+#endif //#ifndef _SPARSE_ROW_H_
Index: /issm/trunk/src/c/toolkits/issm/issmtoolkit.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 16560)
@@ -22,4 +22,5 @@
 #ifdef _HAVE_MPI_
 #include "./IssmMpiDenseMat.h"
+#include "./IssmMpiSparseMat.h"
 #include "./IssmMpiVec.h"
 #endif
Index: /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 16559)
+++ /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 16560)
@@ -41,4 +41,5 @@
 		for(j=lower_row;j<upper_row;j++)RowRank[j]=i;
 	}
+	xDelete<int>(alllocalsizes);
 
 	return RowRank;
Index: /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp	(revision 16559)
+++ /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp	(revision 16560)
@@ -110,5 +110,5 @@
 }/*}}}*/
 int ISSM_MPI_Allreduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, ISSM_MPI_Comm comm){/*{{{*/
- 
+
   int rc=0;
 #ifdef _HAVE_MPI_
@@ -178,5 +178,5 @@
 }/*}}}*/
 int ISSM_MPI_Comm_free(ISSM_MPI_Comm *comm){ /*{{{*/
- 
+
   int rc=0;
 #ifdef _HAVE_MPI_
@@ -203,5 +203,5 @@
 }/*}}}*/
 int ISSM_MPI_Comm_size( ISSM_MPI_Comm comm, int *size){ /*{{{*/
- 
+
   int rc=0;
 #ifdef _HAVE_MPI_
@@ -263,5 +263,5 @@
 }/*}}}*/
 int ISSM_MPI_Gatherv(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcnts, int *displs, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){/*{{{*/
- 
+
   int rc=0;
   assert(sendtype==recvtype); // we handle only identical representations
Index: /issm/trunk/src/c/toolkits/mpi/issmmpi.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 16560)
@@ -51,5 +51,5 @@
 	#define ISSM_MPI_ANY_TAG       MPI_ANY_TAG
 	#define ISSM_MPI_ANY_SOURCE    MPI_ANY_SOURCE
-	
+
     /*other include files: */
 	#include "./commops/commops.h"
Index: /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 16559)
+++ /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 16560)
@@ -3,5 +3,5 @@
  */
 
-/*Header files: {{{*/
+/*Header files: */
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -21,8 +21,7 @@
 
 /*Mumps header files: */
-#include "dmumps_c.h"
-/*}}}*/
-
-void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc) { 
+#include <dmumps_c.h>
+
+void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc){ 
 	theMumpsStruc.par          = 1;  
 	theMumpsStruc.sym          = 0;
@@ -35,7 +34,8 @@
 void MumpsSettings(DMUMPS_STRUC_C &theMumpsStruc) { 
 	/*Control statements:{{{ */
-	theMumpsStruc.icntl[1-1] = 6; //error verbose
-	theMumpsStruc.icntl[2-1] = 1; //std verbose
-	theMumpsStruc.icntl[4-1] = 4; //verbose everything
+	theMumpsStruc.icntl[1-1] = 6; //error verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[2-1] = 0; //std verbose: default 1, 0 or negative -> suppressed
+	theMumpsStruc.icntl[3-1] = 0; //global information verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[4-1] = 0; //verbose everything: default is 4
 	theMumpsStruc.icntl[5-1] = 0;
 	theMumpsStruc.icntl[18-1] = 3;
@@ -71,18 +71,11 @@
 }
 
-void MumpsSolve(int n,
-		int nnz,
-		int local_nnz,
-		int* irn_loc,
-		int* jcn_loc,
-		IssmPDouble *a_loc,
-		IssmPDouble *rhs,
-		Parameters* parameters=0 /*unused here*/) {
-	/*Initialize mumps: {{{*/
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc, IssmPDouble *a_loc, IssmPDouble *rhs, Parameters* parameters=0 /*unused here*/){
+	/*Initialize mumps*/
 	DMUMPS_STRUC_C theMumpsStruc;
 	MumpsInit(theMumpsStruc);
 	MumpsSettings(theMumpsStruc);
-	/*}}}*/
-	// now setup the rest of theMumpsStruc 
+
+	/*now setup the rest of theMumpsStruc */
 	theMumpsStruc.n=n;
 	theMumpsStruc.nz=nnz;
@@ -94,9 +87,9 @@
 	theMumpsStruc.nrhs=1;
 	theMumpsStruc.lrhs=1;
-	/*Solve system: {{{*/
+
+	/*Solve system*/
 	MumpsAnalyze(theMumpsStruc);
 	MumpsFactorize(theMumpsStruc);
 	MumpsBacksubstitute(theMumpsStruc);
-	/*}}}*/
 	MumpsFinalize(theMumpsStruc);
 }
@@ -116,34 +109,29 @@
 void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
 
-	/*Variables: {{{*/
-
-	ISSM_MPI_Comm   comm;
-	int        my_rank;
-	int        num_procs;
-	int        i;
-	int        j;
-	int         nnz       ,local_nnz;
-	int        *irn_loc = NULL;
-	int        *jcn_loc = NULL;
-	IssmDouble *a_loc   = NULL;
-	int         count;
-	int         lower_row;
-	int         upper_row;
-	IssmDouble* rhs=NULL;
-	int*        recvcounts=NULL;
-	int*        displs=NULL;
-	/*}}}*/
-	/*Communicator info:{{{ */
-	my_rank=IssmComm::GetRank();
-	num_procs=IssmComm::GetSize();
-	comm=IssmComm::GetComm();
-	/*}}}*/
-	/*First, some checks:{{{ */
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i,j;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
 	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
-	if (uf_M!=Kff_M | uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
-	if (uf_m!=Kff_m | uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
-	/*}}}*/
-	/*Initialize matrix:{{{ */
-
+	if (uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if (uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
 	/*figure out number of non-zero entries: */
 	local_nnz=0;
@@ -192,18 +180,10 @@
 	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
 
-	MumpsSolve(Kff_M,
-		   nnz,
-		   local_nnz,
-		   irn_loc,
-		   jcn_loc,
-		   a_loc,
-		   rhs,
-		   parameters);
-
-	/*Now scatter from cpu 0 to all other cpus: {{{*/
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
 	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
 
-	/*}}}*/
-	/*Cleanup: {{{*/
+	/*Cleanup*/
 	xDelete<int>(irn_loc);
 	xDelete<int>(jcn_loc);
@@ -212,5 +192,4 @@
 	xDelete<int>(recvcounts);
 	xDelete<int>(displs);
-	/*}}}*/
 } /*}}}*/
 
@@ -245,12 +224,5 @@
 }
 
-void MumpsSolve(int n,
-		int nnz,
-		int local_nnz,
-		int* irn_loc,
-		int* jcn_loc,
-		IssmDouble *a_loc,
-		IssmDouble *rhs,
-		Parameters* parameters) {
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){
   int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
   int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
Index: /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 16560)
+++ /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 16560)
@@ -0,0 +1,396 @@
+/*!\file MumpsSolve.cpp
+ * \brief: solve dense matrix system with MUMPS
+ */
+
+/*Header files: */
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/io/Comm/IssmComm.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../mpi/issmmpi.h"
+#include "../adolc/adolcincludes.h"
+#include "../issm/SparseRow.h"
+#include "./mumpsincludes.h"
+
+/*Mumps header files: */
+#include <dmumps_c.h>
+
+void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc){ 
+	theMumpsStruc.par          = 1;  
+	theMumpsStruc.sym          = 0;
+	theMumpsStruc.comm_fortran = MPI_Comm_c2f(IssmComm::GetComm());
+	theMumpsStruc.job          = -1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsSettings(DMUMPS_STRUC_C &theMumpsStruc) { 
+	/*Control statements:{{{ */
+	theMumpsStruc.icntl[1-1] = 6; //error verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[2-1] = 0; //std verbose: default 1, 0 or negative -> suppressed
+	theMumpsStruc.icntl[3-1] = 0; //global information verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[4-1] = 0; //verbose everything: default is 4
+	theMumpsStruc.icntl[5-1] = 0;
+	theMumpsStruc.icntl[18-1] = 3;
+
+	theMumpsStruc.icntl[20-1] = 0;
+	theMumpsStruc.icntl[21-1] = 0;
+	theMumpsStruc.icntl[30-1] = 0;
+	/*}}}*/
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsAnalyze(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsAnalyze
+void MumpsFactorize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 2;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsFactorize
+void MumpsBacksubstitute(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 3;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded at least  by a call to MumpsInit
+void MumpsFinalize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = -2;
+	dmumps_c(&theMumpsStruc);
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc, IssmPDouble *a_loc, IssmPDouble *rhs, Parameters* parameters=0 /*unused here*/){
+	/*Initialize mumps*/
+	DMUMPS_STRUC_C theMumpsStruc;
+	MumpsInit(theMumpsStruc);
+	MumpsSettings(theMumpsStruc);
+
+	/*now setup the rest of theMumpsStruc */
+	theMumpsStruc.n=n;
+	theMumpsStruc.nz=nnz;
+	theMumpsStruc.nz_loc=local_nnz;
+	theMumpsStruc.irn_loc=irn_loc;
+	theMumpsStruc.jcn_loc=jcn_loc;
+	theMumpsStruc.a_loc=a_loc;
+	theMumpsStruc.rhs=rhs;
+	theMumpsStruc.nrhs=1;
+	theMumpsStruc.lrhs=1;
+
+	/*Solve system*/
+	MumpsAnalyze(theMumpsStruc);
+	MumpsFactorize(theMumpsStruc);
+	MumpsBacksubstitute(theMumpsStruc);
+	MumpsFinalize(theMumpsStruc);
+}
+
+#ifdef _HAVE_ADOLC_
+// prototype for active variant
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmDouble *a_loc,
+		IssmDouble *rhs,
+		Parameters* parameters);
+#endif 
+
+void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
+
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i,j;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
+	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if (uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if (uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
+	/*figure out number of non-zero entries: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0)local_nnz++;
+		}
+	}
+
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0){
+				irn_loc[count]=lower_row+i+1; //fortran indexing
+				jcn_loc[count]=j+1; //fortran indexing
+				a_loc[count]=Kff[i*Kff_N+j];
+				count++;
+			}
+		}
+	}
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+	/*displs: */
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+	/*Gather:*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
+
+	/*Cleanup*/
+	xDelete<int>(irn_loc);
+	xDelete<int>(jcn_loc);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
+	xDelete<int>(recvcounts);
+	xDelete<int>(displs);
+} /*}}}*/
+
+void MpiSparseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ SparseRow<IssmDouble>** Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
+
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i,j;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
+	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if (uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if (uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
+	/*figure out number of non-zero entries: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		local_nnz+=Kff[i]->Nnz();
+	}
+
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		Kff[i]->SetIrnJcnA(irn_loc,jcn_loc,a_loc,lower_row+i+1,count);
+		count+=Kff[i]->Nnz();
+	}
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+	/*displs: */
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+	/*Gather:*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
+
+	/*Cleanup*/
+	xDelete<int>(irn_loc);
+	xDelete<int>(jcn_loc);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
+	xDelete<int>(recvcounts);
+	xDelete<int>(displs);
+} /*}}}*/
+
+#ifdef _HAVE_ADOLC_
+
+int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *A=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+    local_irn[i]=iArr[3+i];
+    local_jcn[i]=iArr[3+local_nnz+i];
+    A[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_x[local_nnz+i];
+  }
+  MumpsSolve(n,nnz,local_nnz,local_irn,local_jcn,A,rhs_sol);
+  for (int i=0;i<n;++i) {
+    dp_y[i]=rhs_sol[i];
+  }
+  xDelete(rhs_sol);
+  xDelete(A);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 0;
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){
+  int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
+  int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
+  packedDimsSparseArr[0]=n;
+  packedDimsSparseArr[1]=nnz;
+  packedDimsSparseArr[2]=local_nnz;
+  for (int i=0;i<local_nnz;++i) {
+    packedDimsSparseArr[3+i]=irn_loc[i];
+    packedDimsSparseArr[3+local_nnz+i]=jcn_loc[i];
+  }
+  IssmDouble *pack_A_rhs=xNew<IssmDouble>(local_nnz+n);
+  for (int i=0;i<local_nnz;++i) { 
+    pack_A_rhs[i]=a_loc[i];
+  }
+  for (int i=0;i<n;++i) { 
+    pack_A_rhs[local_nnz+i]=rhs[i];
+  }
+  IssmPDouble *passivePack_A_rhs=xNew<IssmPDouble>(local_nnz+n);
+  IssmPDouble *passiveSol=xNew<IssmPDouble>(n);
+  IssmDouble *sol=xNew<IssmDouble>(n);
+  call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	       packedDimsSparseArrLength, packedDimsSparseArr,
+	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
+	       n, passiveSol,sol);
+  for (int i=0;i<n;++i) { 
+    rhs[i]=sol[i];
+  }
+  xDelete(sol);
+  xDelete(passiveSol);
+  xDelete(passivePack_A_rhs);
+  xDelete(pack_A_rhs);
+  xDelete(packedDimsSparseArr);
+}
+
+int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr, 
+			      int m, IssmPDouble *dp_U,
+			      int nPlusNz, IssmPDouble *dp_Z,
+			      IssmPDouble *dp_x, IssmPDouble *dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *a_loc=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+	  local_irn[i]=iArr[3+i];
+	  local_jcn[i]=iArr[3+local_nnz+i];
+	  a_loc[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_U[i];
+  }
+  DMUMPS_STRUC_C theMumpsStruc;
+  MumpsInit(theMumpsStruc);
+  MumpsSettings(theMumpsStruc);
+  theMumpsStruc.n=n;
+  theMumpsStruc.nz=nnz;
+  theMumpsStruc.nz_loc=local_nnz;
+  theMumpsStruc.irn_loc=local_irn;
+  theMumpsStruc.jcn_loc=local_jcn;
+  theMumpsStruc.a_loc=a_loc;
+  theMumpsStruc.rhs=rhs_sol;
+  theMumpsStruc.nrhs=1;
+  theMumpsStruc.lrhs=1;
+  theMumpsStruc.icntl[9-1] = 0; //solve for the transpose
+  MumpsAnalyze(theMumpsStruc);
+  MumpsFactorize(theMumpsStruc);
+  MumpsBacksubstitute(theMumpsStruc);
+  MumpsFinalize(theMumpsStruc);
+  // update the adjoint of the rhs:
+  for (int i=0;i<n;++i) {
+    dp_Z[local_nnz+i]+=rhs_sol[i];
+  }
+  // bcast dp_y (the solution of the forward system)
+  ISSM_MPI_Bcast(dp_y,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // bcast the adjoint of the right-hand-side, i.e. this solution
+  ISSM_MPI_Bcast(rhs_sol,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // update the adjoint of the matrix with the outer product of right-hand-side adjoint and the original solution
+  for (int i=0;i<local_nnz;++i) {
+    dp_Z[i]-=rhs_sol[iArr[3+i]-1]*dp_y[iArr[3+local_nnz+i]-1];
+  }
+  xDelete(rhs_sol);
+  xDelete(a_loc);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 3;
+}
+
+#endif
Index: /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 16560)
@@ -17,6 +17,8 @@
 
 class Parameters;
+template <class doubletype> class SparseRow;
 
 void MpiDenseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, IssmDouble* Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters);
+void MpiSparseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, SparseRow<IssmDouble>** Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters);
 
 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 16559)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 16560)
@@ -170,5 +170,4 @@
 	IssmDouble*     df_local=NULL;
 	int         df_local_size;
-	int         i;
 
 	int*     pressure_indices=NULL;
@@ -188,5 +187,5 @@
 		pressure_num=0;
 		velocity_num=0;
-		for(i=0;i<df_local_size;i++){
+		for(int i=0;i<df_local_size;i++){
 			if (df_local[i]==PressureEnum)pressure_num++;
 			else velocity_num++;
@@ -199,5 +198,5 @@
 		pressure_count=0;
 		velocity_count=0;
-		for(i=0;i<df_local_size;i++){
+		for(int i=0;i<df_local_size;i++){
 			if (df_local[i]==PressureEnum){
 				pressure_indices[pressure_count]=start+i;
Index: sm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp	(revision 16559)
+++ 	(revision )
@@ -1,47 +1,0 @@
-/* \file PetscMatrixToDoubleMatrix.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
-
-#include <string>
-
-/*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
-#include <petscksp.h>
-
-/*Petsc includes: */
-#include "../../../shared/shared.h"
-
-void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat petsc_matrix){
-
-	/*output: */
-	int     i;
-	double* matrix=NULL;
-	int     rows,cols;
-
-	/*Some needed information: */
-	MatGetSize(petsc_matrix,&rows,&cols);
-
-	int* idxm=xNew<int>(rows);
-	int* idxn=xNew<int>(cols);
-
-	for(i=0;i<rows;i++)idxm[i]=i;
-	for(i=0;i<cols;i++)idxn[i]=i;
-
-	matrix=xNew<double>(rows*cols);
-	MatGetValues(petsc_matrix,rows,idxm,cols,idxn,matrix);
-
-	xDelete<int>(idxm);
-	xDelete<int>(idxn);
-
-	/*Assign output pointers: */
-	*pmatrix=matrix;
-	*prows=rows;
-	*pcols=cols;
-}
Index: sm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp	(revision 16559)
+++ 	(revision )
@@ -1,42 +1,0 @@
-/* \file PetscVectorToDoubleVector.cpp
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <string>
-
-/*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
-#include <petscksp.h>
-
-#include "../../../shared/shared.h"
-
-void PetscVectorToDoubleVector(double** pvector, int* prows, Vec petsc_vector){
-
-	int     rows;
-	double *vector = NULL;
-
-	/*Get size of vector: */
-	if(petsc_vector){
-		VecGetSize(petsc_vector,&rows);
-		if(rows){
-			int* idxm=xNew<int>(rows);
-			vector=xNew<double>(rows);
-			for(int i=0;i<rows;i++)idxm[i]=i;
-			VecGetValues(petsc_vector,rows,idxm,vector);
-			xDelete<int>(idxm);
-		}
-	}
-	else{
-		rows=0;
-	}
-
-	/*Assign output pointers: */
-	*pvector=vector;
-	*prows=rows;
-}
Index: sm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp	(revision 16559)
+++ 	(revision )
@@ -1,21 +1,0 @@
-/*!\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/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 16559)
+++ /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 16560)
@@ -34,5 +34,4 @@
 void MatMultPatch(Mat A,Vec X, Vec AX,ISSM_MPI_Comm comm);
 void MatToSerial(double** poutmatrix,Mat matrix,ISSM_MPI_Comm comm);
-void VecDuplicatePatch(Vec* output, Vec input);
 Vec  SerialToVec(double* vector,int vector_size);
 InsertMode ISSMToPetscInsertMode(InsMode mode);
@@ -40,6 +39,3 @@
 MatType ISSMToPetscMatrixType(MatrixType type);
 
-void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat matrix);
-void PetscVectorToDoubleVector(double** pvector, int* prows, Vec vector);
-
 #endif
Index: /issm/trunk/src/dox/issm.dox
===================================================================
--- /issm/trunk/src/dox/issm.dox	(revision 16559)
+++ /issm/trunk/src/dox/issm.dox	(revision 16560)
@@ -47,20 +47,20 @@
 </th>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">478</td><td  bgcolor=#FFFFFF style="text-align:right;">14993</td><td  bgcolor=#FFFFFF style="text-align:right;">17509</td><td  bgcolor=#FFFFFF style="text-align:right;">60128</td><td  bgcolor=#FFFFFF style="text-align:right;">92630</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">492</td><td  bgcolor=#FFFFFF style="text-align:right;">15134</td><td  bgcolor=#FFFFFF style="text-align:right;">17851</td><td  bgcolor=#FFFFFF style="text-align:right;">63296</td><td  bgcolor=#FFFFFF style="text-align:right;">96281</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1037</td><td  bgcolor=#C6E2FF style="text-align:right;">7053</td><td  bgcolor=#C6E2FF style="text-align:right;">14331</td><td  bgcolor=#C6E2FF style="text-align:right;">33157</td><td  bgcolor=#C6E2FF style="text-align:right;">54541</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1057</td><td  bgcolor=#C6E2FF style="text-align:right;">7147</td><td  bgcolor=#C6E2FF style="text-align:right;">14649</td><td  bgcolor=#C6E2FF style="text-align:right;">33842</td><td  bgcolor=#C6E2FF style="text-align:right;">55638</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">381</td><td  bgcolor=#FFFFFF style="text-align:right;">3146</td><td  bgcolor=#FFFFFF style="text-align:right;">3358</td><td  bgcolor=#FFFFFF style="text-align:right;">13275</td><td  bgcolor=#FFFFFF style="text-align:right;">19779</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">383</td><td  bgcolor=#FFFFFF style="text-align:right;">3169</td><td  bgcolor=#FFFFFF style="text-align:right;">3340</td><td  bgcolor=#FFFFFF style="text-align:right;">13334</td><td  bgcolor=#FFFFFF style="text-align:right;">19843</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">115</td><td  bgcolor=#C6E2FF style="text-align:right;">4054</td><td  bgcolor=#C6E2FF style="text-align:right;">6697</td><td  bgcolor=#C6E2FF style="text-align:right;">7601</td><td  bgcolor=#C6E2FF style="text-align:right;">18352</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">119</td><td  bgcolor=#C6E2FF style="text-align:right;">1911</td><td  bgcolor=#C6E2FF style="text-align:right;">2296</td><td  bgcolor=#C6E2FF style="text-align:right;">7443</td><td  bgcolor=#C6E2FF style="text-align:right;">11650</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> m4 </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">213</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">1512</td><td  bgcolor=#FFFFFF style="text-align:right;">1731</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> m4 </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">184</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">1845</td><td  bgcolor=#FFFFFF style="text-align:right;">2035</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> CMake </th><td  bgcolor=#C6E2FF style="text-align:right;">158</td><td  bgcolor=#C6E2FF style="text-align:right;">0</td><td  bgcolor=#C6E2FF style="text-align:right;">835</td><td  bgcolor=#C6E2FF style="text-align:right;">598</td><td  bgcolor=#C6E2FF style="text-align:right;">1433</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> CMake </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">31</td><td  bgcolor=#C6E2FF style="text-align:right;">84</td><td  bgcolor=#C6E2FF style="text-align:right;">637</td><td  bgcolor=#C6E2FF style="text-align:right;">752</td>
 </tr>
 <tr>
@@ -71,5 +71,5 @@
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">58</td><td  bgcolor=#FFFFFF style="text-align:right;">71</td><td  bgcolor=#FFFFFF style="text-align:right;">252</td><td  bgcolor=#FFFFFF style="text-align:right;">381</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">48</td><td  bgcolor=#FFFFFF style="text-align:right;">66</td><td  bgcolor=#FFFFFF style="text-align:right;">213</td><td  bgcolor=#FFFFFF style="text-align:right;">327</td>
 </tr>
 <tr>
@@ -77,5 +77,5 @@
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2190</td><td  bgcolor=#FFFFFF style="text-align:right;">29623</td><td  bgcolor=#FFFFFF style="text-align:right;">43118</td><td  bgcolor=#FFFFFF style="text-align:right;">117454</td><td  bgcolor=#FFFFFF style="text-align:right;">190195</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2074</td><td  bgcolor=#FFFFFF style="text-align:right;">27730</td><td  bgcolor=#FFFFFF style="text-align:right;">38603</td><td  bgcolor=#FFFFFF style="text-align:right;">121541</td><td  bgcolor=#FFFFFF style="text-align:right;">187874</td>
 </tr>
 </table>
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 16559)
+++ /issm/trunk/src/m/Makefile.am	(revision 16560)
@@ -17,5 +17,4 @@
 					./classes/qmu/@dakota_method/*.m \
 					./classes/clusters/*.m \
-					./classes/model/*.m \
 					./consistency/*.m \
 					./array/*.m \
@@ -60,5 +59,4 @@
 					./classes/*.py \
 					./classes/clusters/*.py \
-					./classes/model/*.py \
 					./consistency/*.py \
 					./boundaryconditions/*.py \
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 16560)
@@ -49,8 +49,12 @@
 md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
 
 if (length(md.initialization.temperature)==md.mesh.numberofvertices),
 	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
-	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if isprop(md.mesh,'vertexonsurface')
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
 	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
 		md.basalforcings.geothermalflux=50.*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 16560)
@@ -50,10 +50,11 @@
 	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
 	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
 		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
-		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
-		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if hasattr(md.mesh,'vertexonsurface'):
+			pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+			md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
 		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
 			md.basalforcings.geothermalflux=50.*10**-3*numpy.ones((md.mesh.numberofvertices,1))    #50 mW/m^2
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 16560)
@@ -38,8 +38,10 @@
 
 %First find segments that are not completely on the front
-if(md.mesh.dimension==2),
+if strcmp(meshtype(md.mesh),'3D'),
+	numbernodesfront=4;
+elseif strcmp(meshtype(md.mesh),'2Dhorizontal'),
 	numbernodesfront=2;
-else 
-	numbernodesfront=4;
+else
+	error('mesh type not supported yet');
 end
 segmentsfront=md.mask.ice_levelset(md.mesh.segments(:,1:numbernodesfront))==0;
@@ -80,8 +82,12 @@
 md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
 
 if (length(md.initialization.temperature)==md.mesh.numberofvertices),
 	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
-	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if isprop(md.mesh,'vertexonsurface'),
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
 	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
 		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 16560)
@@ -2,4 +2,5 @@
 import numpy
 from ContourToMesh import *
+from MatlabFuncs import *
 
 def SetIceShelfBC(md,icefrontfile=''):
@@ -43,8 +44,10 @@
 
 	#First find segments that are not completely on the front
-	if md.mesh.dimension==2:
-		numbernodesfront=2
+	if strcmp(md.mesh.meshtype(),'3D'):
+		numbernodesfront=4;
+	elif strcmp(md.mesh.meshtype(),'2Dhorizontal'):
+		numbernodesfront=2;
 	else:
-		numbernodesfront=4
+		raise	error('mesh type not supported yet')
 	if any(md.mask.ice_levelset<=0):
 		values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
@@ -89,10 +92,11 @@
 	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
 	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
 		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
-		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
-		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if hasattr(md.mesh,'vertexonsurface'):
+			pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+			md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
 		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
 			md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 16560)
@@ -23,5 +23,11 @@
 		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
 	end
-	incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	[path,name,ext]=fileparts(icefrontfile);
+	if strcmp(ext,'.shp'),
+		contours=shpread(icefrontfile);
+	elseif strcmp(ext,'.exp'),
+		contours=expread(icefrontfile);
+	end
+	incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,contours,'node',2);
 	vertexonicefront=double(md.mesh.vertexonboundary & incontour);
 else
@@ -92,8 +98,12 @@
 md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
 
 if (length(md.initialization.temperature)==md.mesh.numberofvertices),
 	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
-	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if isprop(md.mesh,'vertexonsurface'),
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
 	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
 		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 16559)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 16560)
@@ -97,10 +97,11 @@
 	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
 	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
 		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
-		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
-		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if hasattr(md.mesh,'vertexonsurface'):
+			pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+			md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
 		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
 			md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 16559)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 16560)
@@ -5,10 +5,18 @@
 
 classdef autodiff
-	properties (SetAccess=public) 
+	properties (SetAccess=public)  
+		% {{{ 
 		isautodiff   = false;
 		dependents   = {};
 		independents = {};
 		driver       = 'fos_forward';
-	end
+		obufsize     = NaN;
+		lbufsize     = NaN;
+		cbufsize     = NaN;
+		tbufsize     = NaN;
+		gcTriggerRatio = NaN;
+		gcTriggerMaxSize = NaN;
+		end
+		%}}}
 	methods
 		function obj = autodiff(varargin) % {{{
@@ -21,5 +29,10 @@
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
-
+		obj.obufsize     = 524288;
+		obj.lbufsize     = 524288;
+		obj.cbufsize     = 524288;
+		obj.tbufsize     = 524288;
+		obj.gcTriggerRatio=2.0;
+		obj.gcTriggerMaxSize=65536;
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -30,4 +43,12 @@
 			%Driver value:
 			md = checkfield(md,'autodiff.driver','values',{'fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'});
+			
+			%buffer values: 
+			md = checkfield(md,'autodiff.obufsize','>=',16);
+			md = checkfield(md,'autodiff.lbufsize','>=',16);
+			md = checkfield(md,'autodiff.cbufsize','>=',16);
+			md = checkfield(md,'autodiff.tbufsize','>=',16);
+			md = checkfield(md,'autodiff.gcTriggerRatio','>=',0);
+			md = checkfield(md,'autodiff.gcTriggerMaxSize','>=',65536);
 
 			%go through our dependents and independents and check consistency: 
@@ -48,4 +69,10 @@
 			fielddisplay(obj,'independents','list of independent variables');
 			fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
+			fielddisplay(obj,'obufsize','Number of operations per buffer (==OBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'lbufsize','Number of locations per buffer (==LBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'cbufsize','Number of values per buffer (==CBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'tbufsize','Number of taylors per buffer (<=TBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
+			fielddisplay(obj,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
 		end % }}}
 		function marshall(obj,md,fid) % {{{
@@ -61,4 +88,12 @@
 			end
 
+			%buffer sizes {{{
+			WriteData(fid,'object',obj,'fieldname','obufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','lbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','cbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','tbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','gcTriggerRatio','format','Double');
+			WriteData(fid,'object',obj,'fieldname','gcTriggerMaxSize','format','Double');
+			%}}}
 			%process dependent variables {{{
 			num_dependent_objects=numel(obj.dependents);
@@ -66,5 +101,5 @@
 
 			if(num_dependent_objects),
-				names=zeros(num_dependent_objects,1);
+				names={};
 				types=zeros(num_dependent_objects,1);
 				indices=zeros(num_dependent_objects,1);
@@ -73,9 +108,9 @@
 					dep=obj.dependents{i};
 
-					names(i)=StringToEnum(dep.name);
+					names{i}=dep.name;
 					types(i)=dep.typetoscalar();
 					indices(i)=dep.index;
 				end
-				WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3);
+				WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray');
 				WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3);
 				WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3);
Index: /issm/trunk/src/m/classes/autodiff.py
===================================================================
--- /issm/trunk/src/m/classes/autodiff.py	(revision 16559)
+++ /issm/trunk/src/m/classes/autodiff.py	(revision 16560)
@@ -14,5 +14,4 @@
 	      autodiff=autodiff();
 	"""
-
 	def __init__(self,*args):    # {{{
 		self.isautodiff   = False
@@ -20,5 +19,10 @@
 		self.independents = []
 		self.driver       = 'fos_forward'
-
+		self.obufsize     = float('NaN')
+		self.lbufsize     = float('NaN')
+		self.cbufsize     = float('NaN')
+		self.tbufsize     = float('NaN')
+		self.gcTriggerMaxSize     = float('NaN')
+		self.gcTriggerRatio     = float('NaN')
 		if not len(args):
 			self.setdefaultparameters()
@@ -33,8 +37,21 @@
 		s+="%s\n" % fielddisplay(self,'independents',"list of independent variables")
 		s+="%s\n" % fielddisplay(self,'driver',"ADOLC driver ('fos_forward' or 'fov_forward')")
+		s+="%s\n" % fielddisplay(self,'obufsize',"Number of operations per buffer (==OBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'lbufsize',"Number of locations per buffer (==LBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'cbufsize',"Number of values per buffer (==CBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'tbufsize',"Number of taylors per buffer (<=TBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'gcTriggerRatio',"free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio")
+		s+="%s\n" % fielddisplay(self,'gcTriggerMaxSize',"free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize)")
 
 		return s
 	# }}}
 	def setdefaultparameters(self):    # {{{
+		
+		self.obufsize     = 524288
+		self.lbufsize     = 524288
+		self.cbufsize     = 524288
+		self.tbufsize     = 524288
+		self.gcTriggerRatio=2.0
+		self.gcTriggerMaxSize=65536
 		return self
 	# }}}
@@ -43,5 +60,12 @@
 		#Early return 
 		if not self.isautodiff:
-			return md
+			return md 
+		
+		md = checkfield(md,'autodiff.obufsize','>=',524288)
+		md = checkfield(md,'autodiff.lbufsize','>=',524288)
+		md = checkfield(md,'autodiff.cbufsize','>=',524288)
+		md = checkfield(md,'autodiff.tbufsize','>=',524288)
+		md = checkfield(md,'autodiff.gcTriggerRatio','>=',2.0)
+		md = checkfield(md,'autodiff.gcTriggerMaxSize','>=',2000000)
 
 		#Driver value:
@@ -65,5 +89,13 @@
 			WriteData(fid,'data',False,'enum',AutodiffKeepEnum(),'format','Boolean')
 			return
-
+			
+		#buffer sizes {{{
+		WriteData(fid,'object',self,'fieldname','obufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','lbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','cbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','tbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','gcTriggerRatio','format','Double');
+		WriteData(fid,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
+		#}}}
 		#process dependent variables {{{
 		num_dependent_objects=len(self.dependents)
@@ -71,18 +103,17 @@
 
 		if num_dependent_objects:
-			names=numpy.zeros(num_dependent_objects)
+			names=[]
 			types=numpy.zeros(num_dependent_objects)
 			indices=numpy.zeros(num_dependent_objects)
 
 			for i,dep in enumerate(self.dependents):
-				names[i]=StringToEnum(dep.name)[0]
+				names[i]=dep.name
 				types[i]=dep.typetoscalar()
 				indices[i]=dep.index
 
-			WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3)
+			WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray')
 			WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3)
 			WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3)
 		#}}}
-
 		#process independent variables {{{
 		num_independent_objects=len(self.independents)
@@ -100,5 +131,4 @@
 			WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3)
 		#}}}
-
 		#if driver is fos_forward, build index:  {{{
 		if strcmpi(self.driver,'fos_forward'):
@@ -118,5 +148,4 @@
 			WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer')
 		#}}}
-
 		#if driver is fos_reverse, build index:  {{{
 		if strcmpi(self.driver,'fos_reverse'):
@@ -136,5 +165,4 @@
 			WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer')
 		#}}}
-
 		#if driver is fov_forward, build indices:  {{{
 		if strcmpi(self.driver,'fov_forward'):
@@ -154,5 +182,4 @@
 			WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3)
 		#}}}
-
 		#deal with mass fluxes:  {{{
 		mass_flux_segments=[dep.segments for dep in self.dependents if strcmpi(dep.name,'MassFlux')]
@@ -165,5 +192,4 @@
 		WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
 		#}}}
-
 		#deal with trace keep on: {{{
 		keep=False
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 16559)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 16560)
@@ -87,6 +87,17 @@
 					 end
 				 end
-			 else
-				 md = checkmessage(md,'unknown processor type, should be ''neh'',''wes'' or ''har''');
+			 elseif strcmpi(cluster.processor,'ivy'),
+				 if cluster.hyperthreading,
+					 if ((cluster.cpuspernode>40 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 40 for ''ivy'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>20 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 20 for ''ivy'' processors');
+					 end
+				 end
+
+			 else
+				 md = checkmessage(md,'unknown processor type, should be ''neh'',''wes'' or ''har'' or ''ivy''');
 			 end
 
Index: /issm/trunk/src/m/classes/damage.m
===================================================================
--- /issm/trunk/src/m/classes/damage.m	(revision 16560)
+++ /issm/trunk/src/m/classes/damage.m	(revision 16560)
@@ -0,0 +1,157 @@
+%DAMAGEICE class definition
+%
+%   Usage:
+%      damage=damage();
+
+classdef damage
+	properties (SetAccess=public)  
+		%damage 
+		D                   = NaN;
+		law                 = '';
+		spcdamage           = NaN; 
+		max_damage          = NaN;
+	
+		%numerical
+		stabilization       = NaN;
+		penalty_threshold   = NaN;
+		maxiter             = NaN;
+		penalty_lock        = NaN;
+		penalty_factor      = NaN;
+		
+		%general parameters for evolution law: 
+		stress_threshold    = NaN;
+		c1                  = NaN;
+		c2                  = NaN;
+		c3                  = NaN;
+		c4                  = NaN;
+		healing             = NaN;
+	end
+	methods
+		function obj = damage(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('damage');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%damage parameters: 
+			obj.D=0;
+			obj.law='undamaged';
+			
+			obj.max_damage=1-1e-5; %if damage reaches 1, solve becomes singular, as viscosity becomes nil
+		
+			%Type of stabilization used
+			obj.stabilization=2;
+			
+			%Maximum number of iterations
+			obj.maxiter=100;
+
+			%factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+			
+			%stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)
+			obj.penalty_lock=0;
+			
+			%threshold to declare convergence of thermal solution (default is 0)
+			obj.penalty_threshold=0;
+		
+			%damage evolution parameters 
+			obj.stress_threshold=0;
+			obj.healing=0;
+			obj.c1=0;
+			obj.c2=0;
+			obj.c3=0;
+			obj.c4=0;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			
+			md = checkfield(md,'damage.D','>=',0,'<=',obj.max_damage,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'damage.max_damage','<',1,'>=',0);
+			md = checkfield(md,'damage.law','values',{'undamaged','pralong'});
+			md = checkfield(md,'damage.spcdamage','forcing',1);
+			
+			md = checkfield(md,'damage.stabilization','numel',[1],'values',[0 1 2]);
+			md = checkfield(md,'damage.maxiter','>=0',0);
+			md = checkfield(md,'damage.penalty_factor','>=0',0);
+			md = checkfield(md,'damage.penalty_lock','>=0',0);
+			md = checkfield(md,'damage.penalty_threshold','>=0',0);
+
+			if strcmpi(obj.law,'pralong'),
+				md = checkfield(md,'damage.healing','>=',0);
+				md = checkfield(md,'damage.c1','>=',0);
+				md = checkfield(md,'damage.c2','>=',0);
+				md = checkfield(md,'damage.c3','>=',0);
+				md = checkfield(md,'damage.c4','>=',0);
+				md = checkfield(md,'damage.stress_threshold','>=',0);
+			elseif strcmpi(obj.law,'undamaged'),
+				if (solution==DamageEvolutionSolutionEnum),
+					error('Invalid evolution law (md.damage.law) for a damage solution');
+				end
+			else 
+				error('invalid damage evolution law');
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Damage:\n'));
+
+			fielddisplay(obj,'D','damage tensor (scalar)');
+			fielddisplay(obj,'law','damage law (string) from {''undamaged'',''pralong''}');
+			fielddisplay(obj,'spcdamage','damage constraints (NaN means no constraint)');
+			fielddisplay(obj,'max_damage','maximum possible damage (0<=max_damage<1)');
+			
+			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
+			fielddisplay(obj,'maxiter','maximum number of non linear iterations');
+			fielddisplay(obj,'penalty_lock','stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+			fielddisplay(obj,'penalty_threshold','threshold to declare convergence of damage evolution solution (default is 0)');
+			fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
+
+			if strcmpi(obj.law,'pralong'),
+				fielddisplay(obj,'c1','damage parameter 1');
+				fielddisplay(obj,'c2','damage parameter 2');
+				fielddisplay(obj,'c3','damage parameter 3');
+				fielddisplay(obj,'c4','damage parameter 4');
+				fielddisplay(obj,'healing','damage healing parameter 1');
+				fielddisplay(obj,'stress_threshold','damage stress threshold [Pa]');
+			end
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+		
+			WriteData(fid,'object',obj,'fieldname','D','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','law','format','String');
+			WriteData(fid,'object',obj,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','max_damage','format','Double');
+
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','penalty_threshold','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');
+	
+			if strcmpi(obj.law,'pralong'),
+				WriteData(fid,'object',obj,'fieldname','c1','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c2','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c3','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c4','format','Double');
+				WriteData(fid,'object',obj,'fieldname','stress_threshold','format','Double');
+				WriteData(fid,'object',obj,'fieldname','healing','format','Double');
+			end
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/damage.py
===================================================================
--- /issm/trunk/src/m/classes/damage.py	(revision 16560)
+++ /issm/trunk/src/m/classes/damage.py	(revision 16560)
@@ -0,0 +1,144 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+
+class damage(object):
+	"""
+	DAMAGE class definition
+
+	   Usage:
+	      damage=damage();
+	"""
+
+	def __init__(self,*args):    # {{{
+			
+		#damage: 
+		self.D						= float('NaN')
+		self.law						= ''
+		self.spcdamage				= float('NaN')
+		self.max_damage			= float('NaN')
+		
+		#numerical
+		stabilization				= float('NaN')
+		penalty_threshold			= float('NaN')
+		maxiter						= float('NaN')
+		penalty_lock				= float('NaN')
+		penalty_factor				= float('NaN')
+
+		#general parameters for evolution law: 
+		self.stress_threshold   = float('NaN')
+		self.c1                 = float('NaN')
+		self.c2                 = float('NaN')
+		self.c3                 = float('NaN')
+		self.c4                 = float('NaN')
+		self.healing				= float('NaN')
+
+		if not len(args):
+			self.setdefaultparameters()
+		else:
+			raise RuntimeError("constructor not supported")
+
+	# }}}
+	def __repr__(self):    # {{{
+		s ='   Damage:\n'
+
+		s+="%s\n" % fielddisplay(self,"D","damage tensor (scalar for now)")
+		s+="%s\n" % fielddisplay(self,"law","damage law (string) from ['undamaged','pralong']")
+		s+="%s\n" % fielddisplay(self,"spcdamage","damage constraints (NaN means no constraint)")
+		s+="%s\n" % fielddisplay(self,"max_damage","maximum possible damage (0<=max_damage<1)")
+
+		s+="%s\n" % fielddisplay(self,"stabilization","0: no, 1: artificial_diffusivity, 2: SUPG")
+		s+="%s\n" % fielddisplay(self,"maxiter","maximum number of non linear iterations")
+		s+="%s\n" % fielddisplay(self,"penalty_lock","stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)")
+		s+="%s\n" % fielddisplay(self,"penalty_lock","threshold to declare convergence of damage evolution solution (default is 0)")
+		s+="%s\n" % fielddisplay(self,"penalty_lock","scaling exponent (default is 3)")
+
+		if (self.law=='pralong'):
+			s+="%s\n" % fielddisplay(self,"c1","damage parameter 1 ")
+			s+="%s\n" % fielddisplay(self,"c2","damage parameter 2 ")
+			s+="%s\n" % fielddisplay(self,"c3","damage parameter 3 ")
+			s+="%s\n" % fielddisplay(self,"c4","damage parameter 4 ")
+			s+="%s\n" % fielddisplay(self,"stress_threshold","damage stress threshold [Pa]")
+
+		return s
+	# }}}
+	def setdefaultparameters(self):    # {{{
+
+		#damage parameters: 
+		self.D=0
+		self.law='undamaged'
+
+		self.max_damage=1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil
+		
+		#Type of stabilization used
+		self.stabilization=2
+			
+		#Maximum number of iterations
+		self.maxiter=100
+
+		#factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+			
+		#stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)
+		self.penalty_lock=0
+			
+		#threshold to declare convergence of thermal solution (default is 0)
+		self.penalty_threshold=0
+		
+		#damage evolution parameters 
+		self.stress_threshold=0
+		self.c1=0
+		self.c2=0
+		self.c3=0
+		self.c4=0
+		self.healing=0
+
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'damage.D','>=',0,'<=',self.max_damage,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'damage.max_damage','<',1,'>=',0)
+		md = checkfield(md,'damage.law','values',['undamaged','pralong'])
+		md = checkfield(md,'damage.spcdamage','forcing',1)
+			
+		md = checkfield(md,'damage.stabilization','numel',[1],'values',[0,1,2]);
+		md = checkfield(md,'damage.maxiter','>=0',0);
+		md = checkfield(md,'damage.penalty_factor','>=0',0);
+		md = checkfield(md,'damage.penalty_lock','>=0',0);
+		md = checkfield(md,'damage.penalty_threshold','>=0',0);
+
+		if self.law == 'pralong':
+			md = checkfield(md,'damage.healing','>=',0);
+			md = checkfield(md,'damage.c1','>=',0)
+			md = checkfield(md,'damage.c2','>=',0)
+			md = checkfield(md,'damage.c3','>=',0)
+			md = checkfield(md,'damage.c4','>=',0)
+			md = checkfield(md,'damage.stress_threshold','>=',0)
+		elif strcmpi(self.law,'undamaged'):
+			if (solution==DamageEvolutionSolutionEnum):
+				raise RuntimeError('Invalid evolution law (md.damage.law) for a damage solution');
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','law','format','String')
+		WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+		WriteData(fid,'object',self,'fieldname','max_damage','format','Double');
+
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer');
+		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer');
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer');
+		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer');
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double');
+
+		if self.law=='pralong':
+			WriteData(fid,'object',self,'fieldname','c1','format','Double')
+			WriteData(fid,'object',self,'fieldname','c2','format','Double')
+			WriteData(fid,'object',self,'fieldname','c3','format','Double')
+			WriteData(fid,'object',self,'fieldname','c4','format','Double')
+			WriteData(fid,'object',self,'fieldname','stress_threshold','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 16559)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 16560)
@@ -91,10 +91,15 @@
 				md = checkfield(md,'flowequation.borderHO','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				md = checkfield(md,'flowequation.borderFS','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				if (md.mesh.dimension==2),
+				if strcmp(meshtype(md.mesh),'2Dhorizontal')
 					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
 					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
-				else
+				elseif strcmp(meshtype(md.mesh),'2Dvertical')
+					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[4]);
+					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[4]);
+				elseif strcmp(meshtype(md.mesh),'3D'),
 					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
 					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
+				else
+					error('Case not supported yet');
 				end
 				if ~(obj.isSIA || obj.isSSA || obj.isL1L2 || obj.isHO || obj.isFS),
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 16559)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 16560)
@@ -79,10 +79,12 @@
 			md = checkfield(md,'flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
 			md = checkfield(md,'flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
-			if md.mesh.dimension==2:
+			if strcmp(md.mesh.meshtype(),'2Dhorizontal'):
 				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
 				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
-			else:
+			elif strcmp(md.mesh.meshtype(),'3D'):
 				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
 				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
+			else:
+				raise RuntimeError('mesh type not supported yet')
 			if not (self.isSIA or self.isSSA or self.isL1L2 or self.isHO or self.isFS):
 				md.checkmessage("no element types set for this model")
Index: /issm/trunk/src/m/classes/initialization.m
===================================================================
--- /issm/trunk/src/m/classes/initialization.m	(revision 16559)
+++ /issm/trunk/src/m/classes/initialization.m	(revision 16560)
@@ -51,8 +51,10 @@
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				if strcmp(meshtype(md.mesh),'3D')
+					md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
 				md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum(),
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy)
 				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices 1]);
@@ -104,4 +106,12 @@
 			WriteData(fid,'data',obj.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum);
 			WriteData(fid,'data',obj.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
+
+			if md.thermal.isenthalpy,
+				tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
+				pos  = find(md.initialization.temperature>tpmp);
+				enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
+				enthalpy(pos) = md.materials.heatcapacity*tpmp(pos) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction(pos);
+				WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
+			end
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 16559)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 16560)
@@ -65,7 +65,8 @@
 			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
-			md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
+			if strcmp(md.mesh.meshtype(),'3D'):
+				md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices])
-		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy) or solution==EnthalpySolutionEnum():
+		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy):
 			md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
@@ -86,3 +87,11 @@
 		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
 		WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum())
+
+		if md.thermal.isenthalpy:
+			tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
+			pos  = numpy.nonzero(md.initialization.temperature > tpmp)[0]
+			enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
+			enthalpy[pos] = md.materials.heatcapacity*tpmp[pos].reshape(-1,1) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,1)
+			WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
+
 	# }}}
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 16559)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 16560)
@@ -19,5 +19,4 @@
 		max_parameters              = NaN
 		step_threshold              = NaN
-		gradient_only               = 0
 		vx_obs                      = NaN
 		vy_obs                      = NaN
@@ -50,5 +49,4 @@
 						obj.step_threshold              = .99*ones(in.nsteps,1);
 						obj.vx_obs                      = in.vx_obs;
-						obj.gradient_only               = 0;
 						obj.vy_obs                      = in.vy_obs;
 						obj.vz_obs                      = in.vz_obs;
@@ -88,5 +86,5 @@
 
 			%several responses can be used:
-			obj.cost_functions=101*ones(obj.nsteps,1);
+			obj.cost_functions=101;
 
 			%step_threshold is used to speed up control method. When
@@ -95,7 +93,4 @@
 			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
@@ -116,11 +111,10 @@
 			md = checkfield(md,'inversion.incomplete_adjoint','values',[0 1]);
 			md = checkfield(md,'inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness'});
-			md = checkfield(md,'inversion.nsteps','numel',1,'>=',1);
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar' 'Vx' 'Vy' 'Thickness'});
+			md = checkfield(md,'inversion.nsteps','numel',1,'>=',0);
 			md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
 			md = checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps 1]);
-			md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps num_costfunc],'values',[101:105 201 501:506]);
+			md = checkfield(md,'inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
 			md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
-			md = checkfield(md,'inversion.gradient_only','values',[0 1]);
 			md = checkfield(md,'inversion.gradient_scaling','size',[md.inversion.nsteps num_controls]);
 			md = checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
@@ -157,5 +151,4 @@
 			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/yr]');
 			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
@@ -189,5 +182,4 @@
 			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,'scale',1./yts);
 			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
Index: /issm/trunk/src/m/classes/inversion.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 16559)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 16560)
@@ -29,5 +29,4 @@
 		self.max_parameters              = float('NaN')
 		self.step_threshold              = float('NaN')
-		self.gradient_only               = 0
 		self.vx_obs                      = float('NaN')
 		self.vy_obs                      = float('NaN')
@@ -54,5 +53,4 @@
 		string="%s\n%s"%(string,fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
 		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
-		string="%s\n%s"%(string,fielddisplay(self,'gradient_only','stop control method solution at gradient'))
 		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/yr]'))
 		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/yr]'))
@@ -95,5 +93,5 @@
 
 		#several responses can be used:
-		self.cost_functions=101*numpy.ones((self.nsteps,1))
+		self.cost_functions=101
 
 		#step_threshold is used to speed up control method. When
@@ -101,7 +99,4 @@
 		#the next step
 		self.step_threshold=.7*numpy.ones(self.nsteps) #30 per cent decrement
-
-		#stop control solution at the gradient computation and return it? 
-		self.gradient_only=0
 
 		#cost_function_threshold is a criteria to stop the control methods.
@@ -119,16 +114,15 @@
 
 		num_controls=numpy.size(md.inversion.control_parameters)
-		num_costfunc=numpy.size(md.inversion.cost_functions,axis=1)
+		num_costfunc=numpy.size(md.inversion.cost_functions)
 
 		md = checkfield(md,'inversion.iscontrol','values',[0,1])
 		md = checkfield(md,'inversion.tao','values',[0,1])
 		md = checkfield(md,'inversion.incomplete_adjoint','values',[0,1])
-		md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','MaterialsRheologyZbar','Vx','Vy'])
-		md = checkfield(md,'inversion.nsteps','numel',[1],'>=',1)
+		md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','DamageDbar','Vx','Vy'])
+		md = checkfield(md,'inversion.nsteps','numel',[1],'>=',0)
 		md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
 		md = checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps])
-		md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps,num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'inversion.cost_functions','size',[num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
 		md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
-		md = checkfield(md,'inversion.gradient_only','values',[0,1])
 		md = checkfield(md,'inversion.gradient_scaling','size',[md.inversion.nsteps,num_controls])
 		md = checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
@@ -165,5 +159,4 @@
 		WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
-		WriteData(fid,'object',self,'fieldname','gradient_only','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
 		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
@@ -178,18 +171,18 @@
 
 		#process cost functions
-		num_cost_functions=numpy.size(self.cost_functions,axis=1)
+		num_cost_functions=numpy.size(self.cost_functions)
 		data=copy.deepcopy(self.cost_functions)
-		data[numpy.nonzero(data==101)]=SurfaceAbsVelMisfitEnum()
-		data[numpy.nonzero(data==102)]=SurfaceRelVelMisfitEnum()
-		data[numpy.nonzero(data==103)]=SurfaceLogVelMisfitEnum()
-		data[numpy.nonzero(data==104)]=SurfaceLogVxVyMisfitEnum()
-		data[numpy.nonzero(data==105)]=SurfaceAverageVelMisfitEnum()
-		data[numpy.nonzero(data==201)]=ThicknessAbsMisfitEnum()
-		data[numpy.nonzero(data==501)]=DragCoefficientAbsGradientEnum()
-		data[numpy.nonzero(data==502)]=RheologyBbarAbsGradientEnum()
-		data[numpy.nonzero(data==503)]=ThicknessAbsGradientEnum()
-		data[numpy.nonzero(data==504)]=ThicknessAlongGradientEnum()
-		data[numpy.nonzero(data==505)]=ThicknessAcrossGradientEnum()
-		WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
+		data=[SurfaceAbsVelMisfitEnum()        if x==101 else x for x in data]
+		data=[SurfaceRelVelMisfitEnum()        if x==102 else x for x in data]
+		data=[SurfaceLogVelMisfitEnum()        if x==103 else x for x in data]
+		data=[SurfaceLogVxVyMisfitEnum()       if x==104 else x for x in data]
+		data=[SurfaceAverageVelMisfitEnum()    if x==105 else x for x in data]
+		data=[ThicknessAbsMisfitEnum()         if x==201 else x for x in data]
+		data=[DragCoefficientAbsGradientEnum() if x==501 else x for x in data]
+		data=[RheologyBbarAbsGradientEnum()    if x==502 else x for x in data]
+		data=[ThicknessAbsGradientEnum()       if x==503 else x for x in data]
+		data=[ThicknessAlongGradientEnum()     if x==504 else x for x in data]
+		data=[ThicknessAcrossGradientEnum()    if x==505 else x for x in data]
+		WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
 		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
 	# }}}
Index: /issm/trunk/src/m/classes/mask.m
===================================================================
--- /issm/trunk/src/m/classes/mask.m	(revision 16559)
+++ /issm/trunk/src/m/classes/mask.m	(revision 16560)
@@ -27,5 +27,5 @@
 			isice=(md.mask.ice_levelset>0);
 			if any(sum(isice(md.mesh.elements),2)==0),
-				error('elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0');
+				warning('elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0');
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/massfluxatgate.m
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.m	(revision 16560)
+++ /issm/trunk/src/m/classes/massfluxatgate.m	(revision 16560)
@@ -0,0 +1,64 @@
+%MASSFLUXATGATE class definition
+%
+%   Usage:
+%      massfluxatgate=massfluxatgate();
+%      massfluxatgate=massfluxatgate('GateName','PathToExpFile');
+
+classdef massfluxatgate
+	properties (SetAccess=public)  
+		%massfluxatgate 
+		name                = '';
+		profilename            = ''; 
+	end
+	properties (SetAccess=private)  
+		segments            = NaN;
+	end
+	methods
+		function obj = massfluxatgate(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj.name=varargin{1};
+				case 2
+					obj.name=varargin{1};
+					obj.profilename=varargin{2};
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			
+			if ~ischar(obj.name),
+				error('massfluxatgate error message: ''name'' field should be a string!');
+			end
+			if ~ischar(obj.profilename),
+				error('massfluxatgate error message: ''profilename'' field should be a string!');
+			end
+
+			%check the profilename points to a file!: 
+			if exist(obj.profilename,'file')~=2,
+				error('massfluxatgate error message: file name for profile corresponding to gate does not point to a legitimate file on disk!');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Massfluxatgate:\n'));
+
+			fielddisplay(obj,'name','identifier for this massfluxatgate response');
+			fielddisplay(obj,'profilename','name of file (shapefile or argus file) defining a profile (or gate)');
+			
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+		%before marshalling, we need to create the segments out of the profilename: 
+		obj.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,obj.profilename);
+
+		%ok, marshall name and segments: 
+		WriteData(fid,'object',obj,'fieldname','name','format','String');
+		WriteData(fid,'object',obj,'fieldname','segments','format','DoubleMat','mattype',1);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/massfluxatgate.py
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.py	(revision 16560)
+++ /issm/trunk/src/m/classes/massfluxatgate.py	(revision 16560)
@@ -0,0 +1,55 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+from MeshProfileIntersection import *
+import os
+
+class massfluxatgate(object):
+	"""
+	MASSFLUXATEGATE class definition
+
+	   Usage:
+		  massfluxatgate=massfluxatgate('GateName','PathToExpFile')
+	"""
+
+	def __init__(self,name,profilename): # {{{
+		self.name           = name
+		self.profilename    = profilename
+		self.segments       = float('NaN')
+
+		#}}}
+	def __repr__(self): # {{{
+
+		string="   Massfluxatgate:"
+		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response'))
+		string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		if  not isinstance(self.name, basestring):
+			raise RuntimeError("massfluxatgate error message: 'name' field should be a string!")
+			
+		if  not isinstance(self.profilename, basestring):
+			raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!") 
+		
+		#check the profilename points to a file!: 
+		if not os.path.isfile(self.profilename):
+			raise RuntimeError("massfluxatgate error message: file name for profile corresponding to gate does not point to a legitimate file on disk!")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		
+		#before marshalling, we need to create the segments out of the profilename: 
+		self.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,self.profilename)[0]
+
+		#ok, marshall name and segments: 
+		WriteData(fid,'object',self,'fieldname','name','format','String')
+		WriteData(fid,'object',self,'fieldname','segments','format','DoubleMat','mattype',1)
+
+	# }}}
Index: /issm/trunk/src/m/classes/masstransport.m
===================================================================
--- /issm/trunk/src/m/classes/masstransport.m	(revision 16559)
+++ /issm/trunk/src/m/classes/masstransport.m	(revision 16560)
@@ -13,5 +13,5 @@
 		 vertex_pairing         = NaN;
 		 penalty_factor         = 0;
-		 requested_outputs      = NaN;
+		 requested_outputs      = {};
 	end
 	methods (Static)
@@ -60,4 +60,9 @@
 			end
 		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			list = {'Thickness','Surface','Bed'};
+
+		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
 
@@ -73,4 +78,7 @@
 			%Hydrostatic adjustment
 			obj.hydrostatic_adjustment='Absolute';
+
+			%default output
+			obj.requested_outputs={'default'};
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -84,7 +92,5 @@
 			md = checkfield(md,'masstransport.stabilization','values',[0 1 2 3]);
 			md = checkfield(md,'masstransport.min_thickness','>',0);
-			if ~isempty(md.masstransport.requested_outputs),
-				md = checkfield(md,'masstransport.requested_outputs','size',[NaN 1]);
-			end
+			md = checkfield(md,'masstransport.requested_outputs','stringrow',1);
 
 		end % }}}
@@ -111,5 +117,13 @@
 			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
 			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
-			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+			
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum,'format','StringArray');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/masstransport.py
===================================================================
--- /issm/trunk/src/m/classes/masstransport.py	(revision 16559)
+++ /issm/trunk/src/m/classes/masstransport.py	(revision 16560)
@@ -21,5 +21,5 @@
 		self.vertex_pairing         = float('NaN')
 		self.penalty_factor         = 0
-		self.requested_outputs      = float('NaN')
+		self.requested_outputs      = []
 
 		#set defaults
@@ -38,4 +38,9 @@
 		return string
 		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		return ['Thickness','Surface','Bed']
+
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -52,4 +57,6 @@
 		self.hydrostatic_adjustment='Absolute'
 
+		#default output
+		self.requested_outputs=['default']
 		return self
 	#}}}
@@ -65,6 +72,5 @@
 		md = checkfield(md,'masstransport.stabilization','values',[0,1,2,3])
 		md = checkfield(md,'masstransport.min_thickness','>',0)
-		if not md.masstransport.requested_outputs:
-			md = checkfield(md,'masstransport.requested_outputs','size',[float('NaN'),1])
+		md = checkfield(md,'masstransport.requested_outputs','stringrow',1)
 
 		return md
@@ -78,4 +84,11 @@
 		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
-		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum(),'format','StringArray')
 	# }}}
Index: sm/trunk/src/m/classes/matdamageice.m
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.m	(revision 16559)
+++ 	(revision )
@@ -1,163 +1,0 @@
-%MATDAMAGEICE class definition
-%
-%   Usage:
-%      matdamageice=matdamageice();
-
-classdef matdamageice
-	properties (SetAccess=public) 
-		rho_ice                    = 0.;
-		rho_water                  = 0.;
-		rho_freshwater             = 0.;
-		mu_water                   = 0.;
-		heatcapacity               = 0.;
-		latentheat                 = 0.;
-		thermalconductivity        = 0.;
-		meltingpoint               = 0.;
-		beta                       = 0.;
-		mixed_layer_capacity       = 0.;
-		thermal_exchange_velocity  = 0.;
-		rheology_B   = NaN;
-		rheology_n   = NaN;
-		rheology_Z   = NaN;
-		rheology_law = '';
-
-		%gia: 
-		lithosphere_shear_modulus  = 0.;
-		lithosphere_density        = 0.;
-		mantle_shear_modulus       = 0.;
-		mantle_density             = 0.;
-
-	end
-	methods
-		function obj = matdamageice(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				case 1
-					inputstruct=varargin{1};
-					list1 = properties('matdamageice');
-					list2 = fieldnames(inputstruct);
-					for i=1:length(list1)
-						fieldname = list1{i};
-						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
-						end
-					end
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			%ice density (kg/m^3)
-			obj.rho_ice=917.;
-
-			%ocean water density (kg/m^3)
-			obj.rho_water=1023.;
-
-			%fresh water density (kg/m^3)
-			obj.rho_freshwater=1000.;
-
-			%water viscosity (N.s/m^2)
-			obj.mu_water=0.001787;  
-
-			%ice heat capacity cp (J/kg/K)
-			obj.heatcapacity=2093.;
-
-			%ice latent heat of fusion L (J/kg)
-			obj.latentheat=3.34*10^5;
-
-			%ice thermal conductivity (W/m/K)
-			obj.thermalconductivity=2.4;
-
-			%the melting point of ice at 1 atmosphere of pressure in K
-			obj.meltingpoint=273.15;
-
-			%rate of change of melting point with pressure (K/Pa)
-			obj.beta=9.8*10^-8;
-
-			%mixed layer (ice-water interface) heat capacity (J/kg/K)
-			obj.mixed_layer_capacity=3974.;
-
-			%thermal exchange velocity (ice-water interface) (m/s)
-			obj.thermal_exchange_velocity=1.00*10^-4;
-
-			%Rheology law: what is the temperature dependence of B with T
-			%available: none, paterson and arrhenius
-			obj.rheology_law='Paterson';
-
-			%GIA: 
-			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
-			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
-			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
-			obj.mantle_density             = 3.34;       % (g/cm^-3)
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			md = checkfield(md,'materials.rho_ice','>',0);
-			md = checkfield(md,'materials.rho_water','>',0);
-			md = checkfield(md,'materials.rho_freshwater','>',0);
-			md = checkfield(md,'materials.mu_water','>',0);
-			md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
-			md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
-
-			if ismember(GiaAnalysisEnum(),analyses),
-				md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',1);
-				md = checkfield(md,'materials.lithosphere_density','>',0,'numel',1);
-				md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',1);
-				md = checkfield(md,'materials.mantle_density','>',0,'numel',1);
-			end
-
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   Materials:\n'));
-
-			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
-			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
-			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
-			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
-			fielddisplay(obj,'thermalconductivity','ice thermal conductivity [W/m/K]');
-			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
-			fielddisplay(obj,'latentheat','latent heat of fusion [J/m^3]');
-			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
-			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
-			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
-			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
-			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
-			fielddisplay(obj,'rheology_Z','rheology multiplier');
-			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
-			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
-			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
-			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
-			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1);
-			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
-
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
-
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/matdamageice.py
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.py	(revision 16559)
+++ 	(revision )
@@ -1,152 +1,0 @@
-from fielddisplay import fielddisplay
-from EnumDefinitions import *
-from StringToEnum import StringToEnum
-from checkfield import *
-from WriteData import *
-
-class matdamageice(object):
-	"""
-	MATDAMAGEICE class definition
-
-	   Usage:
-	      matdamageice=matdamageice();
-	"""
-
-	def __init__(self,*args):    # {{{
-		self.rho_ice                    = 0.
-		self.rho_water                  = 0.
-		self.rho_freshwater             = 0.
-		self.mu_water                   = 0.
-		self.heatcapacity               = 0.
-		self.latentheat                 = 0.
-		self.thermalconductivity        = 0.
-		self.meltingpoint               = 0.
-		self.beta                       = 0.
-		self.mixed_layer_capacity       = 0.
-		self.thermal_exchange_velocity  = 0.
-		self.rheology_B   = float('NaN')
-		self.rheology_n   = float('NaN')
-		self.rheology_Z   = float('NaN')
-		self.rheology_law = ''
-
-		#gia: 
-		self.lithosphere_shear_modulus  = 0.
-		self.lithosphere_density        = 0.
-		self.mantle_shear_modulus       = 0.
-		self.mantle_density             = 0.
-
-		if not len(args):
-			self.setdefaultparameters()
-		else:
-			raise RuntimeError("constructor not supported")
-
-	# }}}
-	def __repr__(self):    # {{{
-		s ='   Materials:\n'
-
-		s+="%s\n" % fielddisplay(self,"rho_ice","ice density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"rho_water","ocean water density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"mu_water","water viscosity [N s/m^2]")
-		s+="%s\n" % fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]")
-		s+="%s\n" % fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]")
-		s+="%s\n" % fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K")
-		s+="%s\n" % fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]")
-		s+="%s\n" % fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]")
-		s+="%s\n" % fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")
-		s+="%s\n" % fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")
-		s+="%s\n" % fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]")
-		s+="%s\n" % fielddisplay(self,"rheology_n","Glen's flow law exponent")
-		s+="%s\n" % fielddisplay(self,"rheology_Z","rheology multiplier")
-		s+="%s\n" % fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson', 'Arrhenius' or 'LliboutryDuval'")
-		s+="%s\n" % fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]")
-		s+="%s\n" % fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]")
-		s+="%s\n" % fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]")
-		s+="%s\n" % fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]")
-
-		return s
-	# }}}
-	def setdefaultparameters(self):    # {{{
-
-		#ice density (kg/m^3)
-		self.rho_ice=917.
-
-		#ocean water density (kg/m^3)
-		self.rho_water=1023.
-
-		#fresh water density (kg/m^3)
-		self.rho_freshwater=1000.
-
-		#water viscosity (N.s/m^2)
-		self.mu_water=0.001787  
-
-		#ice heat capacity cp (J/kg/K)
-		self.heatcapacity=2093.
-
-		#ice latent heat of fusion L (J/kg)
-		self.latentheat=3.34*10**5
-
-		#ice thermal conductivity (W/m/K)
-		self.thermalconductivity=2.4
-
-		#the melting point of ice at 1 atmosphere of pressure in K
-		self.meltingpoint=273.15
-
-		#rate of change of melting point with pressure (K/Pa)
-		self.beta=9.8*10**-8
-
-		#mixed layer (ice-water interface) heat capacity (J/kg/K)
-		self.mixed_layer_capacity=3974.
-
-		#thermal exchange velocity (ice-water interface) (m/s)
-		self.thermal_exchange_velocity=1.00*10**-4
-
-		#Rheology law: what is the temperature dependence of B with T
-		#available: none, paterson and arrhenius
-		self.rheology_law='Paterson'
-
-		# GIA:
-		self.lithosphere_shear_modulus  = 6.7*10**10;  # (Pa)
-		self.lithosphere_density        = 3.32;       # (g/cm^-3)
-		self.mantle_shear_modulus       = 1.45*10**11; # (Pa)
-		self.mantle_density             = 3.34;       # (g/cm^-3)
-	# }}}
-	def checkconsistency(self,md,solution,analyses):    # {{{
-		md = checkfield(md,'materials.rho_ice','>',0)
-		md = checkfield(md,'materials.rho_water','>',0)
-		md = checkfield(md,'materials.rho_freshwater','>',0)
-		md = checkfield(md,'materials.mu_water','>',0)
-		md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
-		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
-		md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices])
-		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius','LliboutryDuval'])
-		md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',[1]);
-		md = checkfield(md,'materials.lithosphere_density','>',0,'numel',[1]);
-		md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',[1]);
-		md = checkfield(md,'materials.mantle_density','>',0,'numel',[1]);
-
-		return md
-	# }}}
-	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer')
-		WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','rho_water','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
-		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
-		WriteData(fid,'object',self,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1)
-		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
-
-		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
-		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
-		WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
-		WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
-	# }}}
Index: /issm/trunk/src/m/classes/mesh.m
===================================================================
--- /issm/trunk/src/m/classes/mesh.m	(revision 16559)
+++ /issm/trunk/src/m/classes/mesh.m	(revision 16560)
@@ -181,9 +181,9 @@
 		end % }}}
 		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',MeshTypeEnum(),'data',StringToEnum(['Mesh' meshtype(obj)]),'format','Integer');
 			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');
@@ -200,4 +200,11 @@
 			WriteData(fid,'object',obj,'fieldname','numberofelements2d','format','Integer');
 		end % }}}
+		function type = meshtype(obj) % {{{
+			if obj.dimension==2,
+				type = '2Dhorizontal';
+			else
+				type = '3D';
+			end
+		end % }}}
 	end
 end
Index: /issm/trunk/src/m/classes/mesh.py
===================================================================
--- /issm/trunk/src/m/classes/mesh.py	(revision 16559)
+++ /issm/trunk/src/m/classes/mesh.py	(revision 16560)
@@ -56,5 +56,4 @@
 		#set defaults
 		self.setdefaultparameters()
-
 		#}}}
 	def __repr__(self): # {{{
@@ -163,10 +162,17 @@
 		return md
 	# }}}
+	def meshtype(self): # {{{
+
+		if self.dimension==2:
+			return "2Dhorizontal"
+		else:
+			return "3D"
+	#}}}
 	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',MeshTypeEnum(),'data',StringToEnum("Mesh"+self.meshtype())[0],'format','Integer');
 		WriteData(fid,'object',self,'fieldname','x','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'fieldname','y','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'fieldname','z','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'fieldname','elements','format','DoubleMat','mattype',2)
-		WriteData(fid,'object',self,'fieldname','dimension','format','Integer')
 		WriteData(fid,'object',self,'fieldname','numberoflayers','format','Integer')
 		WriteData(fid,'object',self,'fieldname','numberofelements','format','Integer')
Index: /issm/trunk/src/m/classes/mesh2d.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.m	(revision 16560)
+++ /issm/trunk/src/m/classes/mesh2d.m	(revision 16560)
@@ -0,0 +1,110 @@
+%MESH2D class definition
+%
+%   Usage:
+%      mesh2d=mesh2d();
+
+classdef mesh2d
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		elements                    = NaN
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonboundary            = NaN
+
+		edges                       = NaN
+		segments                    = NaN
+		segmentmarkers              = NaN
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+
+		extractedvertices           = NaN
+		extractedelements           = NaN
+	end
+	methods
+		function obj = mesh2d(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 3]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'mesh.numberofelements','>',0);
+			md = checkfield(md,'mesh.numberofvertices','>',0);
+			md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+
+			switch(solution),
+				case ThermalSolutionEnum(),
+					md = checkmessage(md,'thermal not supported for 2d mesh');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   2d Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(obj,'segmentmarkers','number associated to each segment');
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Extracted model:'));
+			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
+			fielddisplay(obj,'extractedelements','elements extracted from the model');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',MeshTypeEnum(),'data',StringToEnum(['Mesh' meshtype(obj)]),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+		function t = meshtype(obj) % {{{
+			t = '2Dhorizontal';
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/mesh2d.py
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.py	(revision 16560)
+++ /issm/trunk/src/m/classes/mesh2d.py	(revision 16560)
@@ -0,0 +1,112 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from MatlabFuncs import *
+
+class mesh2d(object):
+	"""
+	MESH2D class definition
+
+	   Usage:
+	      mesh2d=mesh2d();
+	"""
+
+	def __init__(self): # {{{
+		self.x                           = float('NaN');
+		self.y                           = float('NaN');
+		self.elements                    = float('NaN');
+		self.numberofelements            = 0;
+		self.numberofvertices            = 0;
+		self.numberofedges               = 0;
+		
+		self.lat                         = float('NaN');
+		self.long                        = float('NaN');
+		self.hemisphere                  = float('NaN');
+
+		self.vertexonboundary            = float('NaN');
+		self.edges                       = float('NaN');
+		self.segments                    = float('NaN');
+		self.segmentmarkers              = float('NaN');
+		self.vertexconnectivity          = float('NaN');
+		self.elementconnectivity         = float('NaN');
+		self.average_vertex_connectivity = 0;
+
+		self.extractedvertices           = float('NaN');
+		self.extractedelements           = float('NaN');
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   2d Mesh:" 
+
+		string="%s\n%s"%(string,"\n      Elements and vertices:")
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","vertex indices of the mesh elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
+
+		string="%s%s"%(string,"\n\n      Properties:")
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
+		string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+
+		string="%s%s"%(string,"\n\n      Extracted model:")
+		string="%s\n%s"%(string,fielddisplay(self,"extractedvertices","vertices extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedelements","elements extracted from the model"))
+
+		string="%s%s"%(string,"\n\n      Projection:")
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#the connectivity is the averaged number of nodes linked to a
+		#given node through an edge. This connectivity is used to initially
+		#allocate memory to the stiffness matrix. A value of 16 seems to
+		#give a good memory/time ration. This value can be checked in
+		#trunk/test/Miscellaneous/runme.m
+		self.average_vertex_connectivity=25
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
+		md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,3])
+		if numpy.any(numpy.logical_not(ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
+			md.checkmessage("orphan nodes have been found. Check the mesh outline")
+		md = checkfield(md,'mesh.numberofelements','>',0)
+		md = checkfield(md,'mesh.numberofvertices','>',0)
+		md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
+		if solution==ThermalSolutionEnum():
+			md.checkmessage("thermal not supported for 2d mesh")
+
+		return md
+	# }}}
+	def meshtype(self): # {{{
+		return "2Dhorizontal"
+	#}}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',MeshTypeEnum(),'data',StringToEnum("Mesh"+self.meshtype())[0],'format','Integer');
+		WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
+		WriteData(fid,'enum',MeshZEnum(),'data',numpy.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
+		WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
+	# }}}
Index: /issm/trunk/src/m/classes/mesh2dvertical.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 16560)
+++ /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 16560)
@@ -0,0 +1,223 @@
+%MESH2DVERTICAL class definition
+%
+%   Usage:
+%      mesh2dvertical=mesh2dvertical();
+
+classdef mesh2dvertical
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		elements                    = NaN
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonboundary            = NaN
+		vertexonbed                 = NaN
+		vertexonsurface             = NaN
+
+		edges                       = NaN
+		segments                    = NaN
+		segmentmarkers              = NaN
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+	end
+	methods
+		function obj = mesh2dvertical(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('mesh2dvertical');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 3]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'mesh.numberofelements','>',0);
+			md = checkfield(md,'mesh.numberofvertices','>',0);
+			md = checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+
+			switch(solution),
+				case ThermalSolutionEnum(),
+					md = checkmessage(md,'thermal not supported for 2d mesh');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   2d vertical Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(obj,'vertexonbed','vertices on the bed of the domain flag list');
+			fielddisplay(obj,'vertexonsurface','vertices on the surface of the domain flag list');
+			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(obj,'segmentmarkers','number associated to each segment');
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',MeshTypeEnum(),'data',StringToEnum(['Mesh' meshtype(obj)]),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbed','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+		function t = meshtype(obj) % {{{
+			t = '2Dvertical';
+		end % }}}
+		function flags = vertexflags(self,value) % {{{
+			flags = zeros(self.numberofvertices,1);
+			pos   = self.segments(find(self.segmentmarkers==value),1:2);
+			flags(pos) = 1;
+		end % }}}
+		function [data datatype] = processdata(self,md,data,options) % {{{
+
+			%transpose data if necessary
+			if (size(data,2) > size(data,1)),
+				data=data';
+			end
+			datasize=size(data);
+
+			%convert to double if necessary
+			if ~isnumeric(data);
+				disp('processdata info message: data is not numeric (logical?). Converted to double');
+				data=double(data);
+			end
+
+			%check length
+			if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements
+				error('plotmodel error message: data not supported yet');
+			end
+
+			%quiver?
+			if datasize(2)>1,
+				datatype=3;
+			end
+
+			%smoothing?
+			if exist(options,'smooth')
+				data=averaging(md,data,getfieldvalue(options,'smooth'));
+				datasize(1)=md.mesh.numberofvertices;
+				%---> go to node data
+			end
+
+			%element data
+			if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+				datatype=1;
+
+				%Mask?
+				if exist(options,'mask'),
+					flags=getfieldvalue(options,'mask');
+					pos=find(~flags);
+					if length(flags)==md.mesh.numberofvertices,
+						[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+						data(pos2,:)=NaN;
+					elseif length(flags)==md.mesh.numberofelements
+						data(pos,:)=NaN;
+					else
+						disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+					end
+				end
+
+				%log?
+				if exist(options,'log'),
+					bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+					data(find(data<bounds(1)))=bounds(1);
+					if any(data<=0),
+						error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+					end
+					pos=find(~isnan(data));
+					data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+				end
+			end
+
+			%node data
+			if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+				datatype=2;
+
+				%Mask?
+				if exist(options,'mask'),
+					flags=getfieldvalue(options,'mask');
+					pos=find(~flags);
+					if length(flags)==md.mesh.numberofvertices,
+						data(pos,:)=NaN;
+					elseif length(flags)==md.mesh.numberofelements
+						data(md.mesh.elements(pos,:),:)=NaN;
+					else
+						disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+					end
+				end
+
+				%log?
+				if exist(options,'log'),
+					%if any(data<=0),
+					%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+					%end
+					data=log(data)/log(getfieldvalue(options,'log'));
+				end
+			end
+		end % }}}
+		function [x y z elements is2d isplanet] = processmesh(self,options) % {{{
+
+			isplanet = 0;
+			is2d     = 1;
+
+			elements = self.elements;
+			x        = self.x;
+			y        = self.y;
+			z        = zeros(self.numberofvertices,1);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/model.m
===================================================================
--- /issm/trunk/src/m/classes/model.m	(revision 16560)
+++ /issm/trunk/src/m/classes/model.m	(revision 16560)
@@ -0,0 +1,1214 @@
+%MODEL class definition
+%
+%   Usage:
+%      md = model(varargin)
+
+classdef model
+	properties (SetAccess=public) %Model fields
+		% {{{
+		%Careful here: no other class should be used as default value this is a bug of matlab
+		mesh             = 0;
+		mask             = 0;
+
+		geometry         = 0;
+		constants        = 0;
+		surfaceforcings  = 0;
+		basalforcings    = 0;
+		materials        = 0;
+		damage           = 0;
+		friction         = 0;
+		flowequation     = 0;
+		timestepping     = 0;
+		initialization   = 0;
+		rifts            = 0;
+
+		debug            = 0;
+		verbose          = 0;
+		settings         = 0;
+		toolkits         = 0;
+		cluster          = 0;
+
+		balancethickness = 0;
+		stressbalance       = 0;
+		groundingline    = 0;
+		hydrology        = 0;
+		masstransport       = 0;
+		thermal          = 0;
+		steadystate      = 0;
+		transient        = 0;
+		gia              = 0;
+
+		autodiff         = 0;
+		flaim            = 0;
+		inversion        = 0;
+		qmu              = 0;
+
+		results          = 0;
+		outputdefinition = 0;
+		radaroverlay     = 0;
+		miscellaneous    = 0;
+		private          = 0;
+
+		%}}}
+	end
+	methods (Static)
+		function md = loadobj(md) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of model and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(md)
+				disp('Recovering model object from a previous version');
+				md = structtomodel(model,md);
+			end
+
+			%2012 August 4th
+			if isa(md.materials,'materials'),
+				disp('Recovering old materials');
+				if numel(md.materials.rheology_Z)==1 & isnan(md.materials.rheology_Z),
+					md.materials=matice(md.materials);
+				else
+					md.materials=matdamageice(md.materials);
+				end
+			end
+			%2013 April 12
+			if numel(md.stressbalance.loadingforce==1)
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+			%2013 April 17
+			if isa(md.hydrology,'hydrology'),
+				disp('Recovering old hydrology class');
+				md.hydrology=hydrologyshreve(md.materials);
+			end
+			%2013 October 9
+			if ~isa(md.damage,'damage'),
+				md.damage=damage();
+				md.damage.D=zeros(md.mesh.numberofvertices,1);
+				md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+			end
+		end% }}}
+	end
+	methods
+		function md = model(varargin) % {{{
+
+			switch nargin
+				case 0
+					md=setdefaultparameters(md);
+				otherwise
+					error('model constructor error message: 0 of 1 argument only in input.');
+				end
+		end
+		%}}}
+		function md = checkmessage(md,string) % {{{
+			if(nargout~=1) error('wrong usage, model must be an output'); end
+			disp(['model not consistent: ' string]);
+			md.private.isconsistent=false;
+		end
+		%}}}
+		function md = collapse(md)% {{{
+			%COLLAPSE - collapses a 3d mesh into a 2d mesh
+			%
+			%   This routine collapses a 3d model into a 2d model
+			%   and collapses all the fileds of the 3d model by
+			%   taking their depth-averaged values
+			%
+			%   Usage:
+			%      md=collapse(md)
+			%
+			%   See also: EXTRUDE, MODELEXTRACT
+
+			%Check that the model is really a 3d model
+			if ~md.mesh.dimension==3,
+				error('collapse error message: only 3d mesh can be collapsed')
+			end
+
+			%Start with changing alle the fields from the 3d mesh 
+
+			%drag is limited to nodes that are on the bedrock.
+			md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+
+			%p and q (same deal, except for element that are on the bedrock: )
+			md.friction.p=project2d(md,md.friction.p,1);
+			md.friction.q=project2d(md,md.friction.q,1);
+
+			%observations
+			if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
+			if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
+			if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
+			if ~isnan(md.inversion.cost_functions_coefficients), md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers); end;
+			if numel(md.inversion.min_parameters)>1, md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers); end;
+			if numel(md.inversion.max_parameters)>1, md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers); end;
+			if ~isnan(md.surfaceforcings.mass_balance),
+				md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers); 
+			end;
+			if ~isnan(md.balancethickness.thickening_rate), md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers); end;
+
+			%results
+			if ~isnan(md.initialization.vx),md.initialization.vx=DepthAverage(md,md.initialization.vx);end;
+			if ~isnan(md.initialization.vy),md.initialization.vy=DepthAverage(md,md.initialization.vy);end;
+			if ~isnan(md.initialization.vz),md.initialization.vz=DepthAverage(md,md.initialization.vz);end;
+			if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
+			if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
+
+			%gia
+			if ~isnan(md.gia.mantle_viscosity), md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1); end
+			if ~isnan(md.gia.lithosphere_thickness), md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1); end
+
+			%bedinfo and surface info
+			md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
+			md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
+			md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
+			md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
+
+			%elementstype
+			if ~isnan(md.flowequation.element_equation)
+				md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
+				md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
+				md.flowequation.borderSSA=project2d(md,md.flowequation.borderSSA,1);
+				md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1);
+				md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1);
+			end	
+
+			%boundary conditions
+			md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers);
+			md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers);
+			md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers);
+			md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers);
+			md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
+			md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
+			md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers)
+			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+			%materials
+			md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+			md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+			
+			%damage: 
+			md.damage.D=DepthAverage(md,md.damage.D);
+
+			%special for thermal modeling:
+			md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1); 
+			md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
+
+			%update of connectivity matrix
+			md.mesh.average_vertex_connectivity=25;
+
+			%Collapse the mesh
+			nodes2d=md.mesh.numberofvertices2d;
+			elements2d=md.mesh.numberofelements2d;
+
+			%parameters
+			md.geometry.surface=project2d(md,md.geometry.surface,1);
+			md.geometry.thickness=project2d(md,md.geometry.thickness,1);
+			md.geometry.bed=project2d(md,md.geometry.bed,1);
+			md.geometry.bathymetry=project2d(md,md.geometry.bathymetry,1);
+			md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
+			md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
+			md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
+			md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+
+			%lat long
+			if numel(md.mesh.lat) ==md.mesh.numberofvertices,  md.mesh.lat=project2d(md,md.mesh.lat,1); end
+			if numel(md.mesh.long)==md.mesh.numberofvertices, md.mesh.long=project2d(md,md.mesh.long,1); end
+
+			%Initialize with the 2d mesh
+			md.mesh.x=md.mesh.x2d;
+			md.mesh.y=md.mesh.y2d;
+			md.mesh.z=zeros(size(md.mesh.x2d));
+			md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+			md.mesh.numberofelements=md.mesh.numberofelements2d;
+			md.mesh.elements=md.mesh.elements2d;
+
+			%Keep a trace of lower and upper nodes
+			md.mesh.lowervertex=NaN;
+			md.mesh.uppervertex=NaN;
+			md.mesh.lowerelements=NaN;
+			md.mesh.upperelements=NaN;
+
+			%Remove old mesh 
+			md.mesh.x2d=NaN;
+			md.mesh.y2d=NaN;
+			md.mesh.elements2d=NaN;
+			md.mesh.numberofelements2d=md.mesh.numberofelements;
+			md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+			md.mesh.numberoflayers=0;
+
+			%Update mesh type
+			md.mesh.dimension=2;
+		end % }}}
+		function md2 = extract(md,area) % {{{
+			%extract - extract a model according to an Argus contour or flag list
+			%
+			%   This routine extracts a submodel from a bigger model with respect to a given contour
+			%   md must be followed by the corresponding exp file or flags list
+			%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+			%   If user wants every element outside the domain to be 
+			%   extract2d, add '~' to the name of the domain file (ex: '~HO.exp');
+			%   an empty string '' will be considered as an empty domain
+			%   a string 'all' will be considered as the entire domain
+			%
+			%   Usage:
+			%      md2=extract(md,area);
+			%
+			%   Examples:
+			%      md2=extract(md,'Domain.exp');
+			%
+			%   See also: EXTRUDE, COLLAPSE
+
+			%copy model
+			md1=md;
+
+			%some checks
+			if ((nargin~=2) | (nargout~=1)),
+				help extract
+				error('extract error message: bad usage');
+			end
+
+			%get elements that are inside area
+			flag_elem=FlagElements(md1,area);
+			if ~any(flag_elem),
+				error('extracted model is empty');
+			end
+
+			%kick out all elements with 3 dirichlets
+			spc_elem=find(~flag_elem);
+			spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
+			flag=ones(md1.mesh.numberofvertices,1);
+			flag(spc_node)=0;
+			pos=find(sum(flag(md1.mesh.elements),2)==0);
+			flag_elem(pos)=0;
+
+			%extracted elements and nodes lists
+			pos_elem=find(flag_elem);
+			pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
+
+			%keep track of some fields
+			numberofvertices1=md1.mesh.numberofvertices;
+			numberofelements1=md1.mesh.numberofelements;
+			numberofvertices2=length(pos_node);
+			numberofelements2=length(pos_elem);
+			flag_node=zeros(numberofvertices1,1);
+			flag_node(pos_node)=1;
+
+			%Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+			Pelem=zeros(numberofelements1,1);
+			Pelem(pos_elem)=[1:numberofelements2]';
+			Pnode=zeros(numberofvertices1,1);
+			Pnode(pos_node)=[1:numberofvertices2]';
+
+			%renumber the elements (some nodes won't exist anymore)
+			elements_1=md1.mesh.elements;
+			elements_2=elements_1(pos_elem,:);
+			elements_2(:,1)=Pnode(elements_2(:,1));
+			elements_2(:,2)=Pnode(elements_2(:,2));
+			elements_2(:,3)=Pnode(elements_2(:,3));
+			if md1.mesh.dimension==3,
+				elements_2(:,4)=Pnode(elements_2(:,4));
+				elements_2(:,5)=Pnode(elements_2(:,5));
+				elements_2(:,6)=Pnode(elements_2(:,6));
+			end
+
+			%OK, now create the new model!
+
+			%take every field from model
+			md2=md1;
+
+			%automatically modify fields
+
+			%loop over model fields
+			model_fields=fields(md1);
+			for i=1:length(model_fields),
+				%get field
+				field=md1.(model_fields{i});
+				fieldsize=size(field);
+				if isobject(field), %recursive call
+					object_fields=fields(md1.(model_fields{i}));
+					for j=1:length(object_fields),
+						%get field
+						field=md1.(model_fields{i}).(object_fields{j});
+						fieldsize=size(field);
+						%size = number of nodes * n
+						if fieldsize(1)==numberofvertices1
+							md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
+						elseif (fieldsize(1)==numberofvertices1+1)
+							md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
+						%size = number of elements * n
+						elseif fieldsize(1)==numberofelements1
+							md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
+						end
+					end
+				else
+					%size = number of nodes * n
+					if fieldsize(1)==numberofvertices1
+						md2.(model_fields{i})=field(pos_node,:);
+					elseif (fieldsize(1)==numberofvertices1+1)
+						md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
+					%size = number of elements * n
+					elseif fieldsize(1)==numberofelements1
+						md2.(model_fields{i})=field(pos_elem,:);
+					end
+				end
+			end
+
+			%modify some specific fields
+
+			%Mesh
+			md2.mesh.numberofelements=numberofelements2;
+			md2.mesh.numberofvertices=numberofvertices2;
+			md2.mesh.elements=elements_2;
+
+			%mesh.uppervertex mesh.lowervertex
+			if md1.mesh.dimension==3
+				md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
+				pos=find(~isnan(md2.mesh.uppervertex));
+				md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
+
+				md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
+				pos=find(~isnan(md2.mesh.lowervertex));
+				md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
+
+				md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
+				pos=find(~isnan(md2.mesh.upperelements));
+				md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
+
+				md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
+				pos=find(~isnan(md2.mesh.lowerelements));
+				md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
+			end
+
+			%Initial 2d mesh 
+			if md1.mesh.dimension==3
+				flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
+				pos_elem_2d=find(flag_elem_2d);
+				flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
+				pos_node_2d=find(flag_node_2d);
+
+				md2.mesh.numberofelements2d=length(pos_elem_2d);
+				md2.mesh.numberofvertices2d=length(pos_node_2d);
+				md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
+				md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
+				md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
+				md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
+
+				md2.mesh.x2d=md1.mesh.x(pos_node_2d);
+				md2.mesh.y2d=md1.mesh.y(pos_node_2d);
+			end
+
+			%Edges
+			if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
+				%renumber first two columns
+				pos=find(md2.mesh.edges(:,4)~=-1);
+				md2.mesh.edges(:  ,1)=Pnode(md2.mesh.edges(:,1));
+				md2.mesh.edges(:  ,2)=Pnode(md2.mesh.edges(:,2));
+				md2.mesh.edges(:  ,3)=Pelem(md2.mesh.edges(:,3));
+				md2.mesh.edges(pos,4)=Pelem(md2.mesh.edges(pos,4));
+				%remove edges when the 2 vertices are not in the domain.
+				md2.mesh.edges=md2.mesh.edges(find(md2.mesh.edges(:,1) & md2.mesh.edges(:,2)),:);
+				%Replace all zeros by -1 in the last two columns
+				pos=find(md2.mesh.edges(:,3)==0);
+				md2.mesh.edges(pos,3)=-1;
+				pos=find(md2.mesh.edges(:,4)==0);
+				md2.mesh.edges(pos,4)=-1;
+				%Invert -1 on the third column with last column (Also invert first two columns!!)
+				pos=find(md2.mesh.edges(:,3)==-1);
+				md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
+				md2.mesh.edges(pos,4)=-1;
+				values=md2.mesh.edges(pos,2);
+				md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
+				md2.mesh.edges(pos,1)=values;
+				%Finally remove edges that do not belong to any element
+				pos=find(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
+				md2.mesh.edges(pos,:)=[];
+			end
+
+			%Penalties
+			if ~isnan(md2.stressbalance.vertex_pairing),
+				for i=1:size(md1.stressbalance.vertex_pairing,1);
+					md2.stressbalance.vertex_pairing(i,:)=Pnode(md1.stressbalance.vertex_pairing(i,:));
+				end
+				md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing(find(md2.stressbalance.vertex_pairing(:,1)),:);
+			end
+			if ~isnan(md2.masstransport.vertex_pairing),
+				for i=1:size(md1.masstransport.vertex_pairing,1);
+					md2.masstransport.vertex_pairing(i,:)=Pnode(md1.masstransport.vertex_pairing(i,:));
+				end
+				md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing(find(md2.masstransport.vertex_pairing(:,1)),:);
+			end
+
+			%recreate segments
+			if md1.mesh.dimension==2
+				md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+				md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+				md2.mesh.segments=contourenvelope(md2);
+				md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+			else
+				%First do the connectivity for the contourenvelope in 2d
+				md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d);
+				md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity);
+				md2.mesh.segments=contourenvelope(md2);
+				md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+				md2.mesh.vertexonboundary=repmat(md2.mesh.vertexonboundary,md2.mesh.numberoflayers,1);
+				%Then do it for 3d as usual
+				md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+				md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+			end
+
+			%Boundary conditions: Dirichlets on new boundary
+			%Catch the elements that have not been extracted
+			orphans_elem=find(~flag_elem);
+			orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
+			%Figure out which node are on the boundary between md2 and md1
+			nodestoflag1=intersect(orphans_node,pos_node);
+			nodestoflag2=Pnode(nodestoflag1);
+			if numel(md1.stressbalance.spcvx)>1 & numel(md1.stressbalance.spcvy)>2 & numel(md1.stressbalance.spcvz)>2,
+				if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
+					md2.stressbalance.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+					md2.stressbalance.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+				else
+					md2.stressbalance.spcvx(nodestoflag2)=NaN;
+					md2.stressbalance.spcvy(nodestoflag2)=NaN;
+					disp(' ')
+					disp('!! extract warning: spc values should be checked !!')
+					disp(' ')
+				end
+				%put 0 for vz
+				md2.stressbalance.spcvz(nodestoflag2)=0;
+			end
+			if ~isnan(md1.thermal.spctemperature),
+				md2.thermal.spctemperature(nodestoflag2,1)=1;
+			end
+
+			%Results fields
+			if isstruct(md1.results),
+				md2.results=struct();
+				solutionfields=fields(md1.results);
+				for i=1:length(solutionfields),
+					if isstruct(md1.results.(solutionfields{i}))
+						%get subfields
+						solutionsubfields=fields(md1.results.(solutionfields{i}));
+						for j=1:length(solutionsubfields),
+							field=md1.results.(solutionfields{i}).(solutionsubfields{j});
+							if length(field)==numberofvertices1,
+								md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
+							elseif length(field)==numberofelements1,
+								md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
+							else
+								md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
+							end
+						end
+					else
+						field=md1.results.(solutionfields{i});
+						if length(field)==numberofvertices1,
+							md2.results.(solutionfields{i})=field(pos_node);
+						elseif length(field)==numberofelements1,
+							md2.results.(solutionfields{i})=field(pos_elem);
+						else
+							md2.results.(solutionfields{i})=field;
+						end
+					end
+				end
+			end
+
+			%Keep track of pos_node and pos_elem
+			md2.mesh.extractedvertices=pos_node;
+			md2.mesh.extractedelements=pos_elem;
+		end % }}}
+		function md = extrude(md,varargin) % {{{
+			%EXTRUDE - vertically extrude a 2d mesh
+			%
+			%   vertically extrude a 2d mesh and create corresponding 3d mesh.
+			%   The vertical distribution can:
+			%    - follow a polynomial law
+			%    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+			%    - be discribed by a list of coefficients (between 0 and 1)
+			%   
+			%
+			%   Usage:
+			%      md=extrude(md,numlayers,extrusionexponent);
+			%      md=extrude(md,numlayers,lowerexponent,upperexponent);
+			%      md=extrude(md,listofcoefficients);
+			%
+			%   Example:
+			%      md=extrude(md,8,3);
+			%      md=extrude(md,8,3,2);
+			%      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
+			%
+			%   See also: MODELEXTRACT, COLLAPSE
+
+			%some checks on list of arguments
+			if ((nargin>4) | (nargin<2) | (nargout~=1)),
+				help extrude;
+				error('extrude error message');
+			end
+
+			%Extrude the mesh
+			if nargin==2, %list of coefficients
+				clist=varargin{1};
+				if any(clist<0) | any(clist>1),
+					error('extrusioncoefficients must be between 0 and 1');
+				end
+				extrusionlist=sort(unique([clist(:);0;1]));
+				numlayers=length(extrusionlist);
+			elseif nargin==3, %one polynomial law
+				if varargin{2}<=0,
+					help extrude;
+					error('extrusionexponent must be >=0');
+				end
+				numlayers=varargin{1};
+				extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
+			elseif nargin==4, %two polynomial laws
+				numlayers=varargin{1};
+				lowerexp=varargin{2};
+				upperexp=varargin{3};
+
+				if varargin{2}<=0 | varargin{3}<=0,
+					help extrude;
+					error('lower and upper extrusionexponents must be >=0');
+				end
+
+				lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
+				upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
+				extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
+
+			end
+
+			if numlayers<2,
+				error('number of layers should be at least 2');
+			end
+			if md.mesh.dimension==3,
+				error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+			end
+
+			%Initialize with the 2d mesh
+			x3d=[]; 
+			y3d=[];
+			z3d=[];  %the lower node is on the bed
+			thickness3d=md.geometry.thickness; %thickness and bed for these nodes
+			bed3d=md.geometry.bed;
+
+			%Create the new layers
+			for i=1:numlayers,
+				x3d=[x3d; md.mesh.x]; 
+				y3d=[y3d; md.mesh.y];
+				%nodes are distributed between bed and surface accordingly to the given exponent
+				z3d=[z3d; bed3d+thickness3d*extrusionlist(i)]; 
+			end
+			number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			%Extrude elements 
+			elements3d=[];
+			for i=1:numlayers-1,
+				elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
+			end
+			number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			%Keep a trace of lower and upper nodes
+			mesh.lowervertex=NaN*ones(number_nodes3d,1);
+			mesh.uppervertex=NaN*ones(number_nodes3d,1);
+			mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
+			mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
+			md.mesh.lowervertex=mesh.lowervertex;
+			md.mesh.uppervertex=mesh.uppervertex;
+
+			%same for lower and upper elements
+			mesh.lowerelements=NaN*ones(number_el3d,1);
+			mesh.upperelements=NaN*ones(number_el3d,1);
+			mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
+			mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
+			md.mesh.lowerelements=mesh.lowerelements;
+			md.mesh.upperelements=mesh.upperelements;
+
+			%Save old mesh 
+			md.mesh.x2d=md.mesh.x;
+			md.mesh.y2d=md.mesh.y;
+			md.mesh.elements2d=md.mesh.elements;
+			md.mesh.numberofelements2d=md.mesh.numberofelements;
+			md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+
+			%Update mesh type
+			md.mesh.dimension=3;
+
+			%Build global 3d mesh 
+			md.mesh.elements=elements3d;
+			md.mesh.x=x3d;
+			md.mesh.y=y3d;
+			md.mesh.z=z3d;
+			md.mesh.numberofelements=number_el3d;
+			md.mesh.numberofvertices=number_nodes3d;
+			md.mesh.numberoflayers=numlayers;
+
+			%Ok, now deal with the other fields from the 2d mesh:
+
+			%lat long
+			md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
+			md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
+
+			%drag coefficient is limited to nodes that are on the bedrock.
+			md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
+
+			%p and q (same deal, except for element that are on the bedrock: )
+			md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
+			md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
+
+			%observations
+			md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
+			md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
+			md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
+			md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
+			md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node');
+			md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
+			md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node');
+
+			%results
+			if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
+			if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
+			if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
+			if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
+			if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
+			if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
+            if ~isnan(md.initialization.watercolumn),md.initialization.watercolumn=project3d(md,'vector',md.initialization.watercolumn,'type','node','layer',1);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.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node');
+			md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node');
+			md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node');
+
+			%boundary conditions
+			md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node');
+			md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node');
+			md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node');
+			md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+			md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node');
+			md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
+			md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node');
+			md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node');
+			md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node');
+
+			%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');
+				
+			%damage
+			md.damage.D=project3d(md,'vector',md.damage.D,'type','node');
+
+			%parameters
+			md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
+			md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+			md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node');
+			md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node');
+			md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
+			md.geometry.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.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node');
+			md.mask.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node');
+			if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+			if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
+			if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
+			if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
+			if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node');end
+			if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node');end
+			if(md.surfaceforcings.isdelta18o),md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node');end
+
+			%Put lithostatic pressure if there is an existing pressure
+			if ~isnan(md.initialization.pressure),
+				md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
+			end
+
+			%special for thermal modeling:
+			md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1); 
+			if ~isnan(md.basalforcings.geothermalflux)
+				md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
+			end
+
+			%increase connectivity if less than 25:
+			if md.mesh.average_vertex_connectivity<=25,
+				md.mesh.average_vertex_connectivity=100;
+			end
+			end % }}}
+		function md = structtomodel(md,structmd) % {{{
+
+			if ~isstruct(structmd) error('input model is not a structure'); end
+
+			%loaded model is a struct, initialize output and recover all fields
+			md = structtoobj(model,structmd);
+
+			%Old field now classes
+			if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
+			if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
+
+			%Field name change
+			if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			if isfield(structmd,'p'), md.friction.p=structmd.p; end
+			if isfield(structmd,'q'), md.friction.q=structmd.p; end
+			if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
+			if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
+			if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
+			if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
+			if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
+			if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
+			if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
+			if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
+			if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
+			if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
+			if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
+			if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.toolkits=structmd.petscoptions; end
+			if isfield(structmd,'g'), md.constants.g=structmd.g; end
+			if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
+			if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
+			if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
+			if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
+			if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
+			if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
+			if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
+			if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
+			if isfield(structmd,'riftproperties'), %old implementation
+				md.rifts=rifts();
+				md.rifts.riftproperties=structmd.riftproperties; 
+				md.rifts.riftstruct=structmd.rifts;
+				md.rifts.riftproperties=structmd.riftinfo;
+			end
+			if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
+			if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
+			if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
+			if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
+			if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
+			if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
+			if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
+			if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
+			if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
+			if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
+			if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
+			if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
+			if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
+			if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
+			if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
+			if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
+			if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
+			if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
+			if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
+			if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
+			if isfield(structmd,'spcthickness'), md.masstransport.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.masstransport.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'hydrostatic_adjustment'), md.masstransport.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
+			if isfield(structmd,'penalties'), md.masstransport.vertex_pairing=structmd.penalties; end
+			if isfield(structmd,'penalty_offset'), md.masstransport.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
+			if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
+			if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
+			if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
+			if isfield(structmd,'rheology_Z'), md.damage.D=(1-structmd.rheology_Z); end
+			if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
+			if isfield(structmd,'isSIA'), md.flowequation.isSIA=structmd.isSIA; end
+			if isfield(structmd,'isFS'), md.flowequation.isFS=structmd.isFS; end
+			if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
+			if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
+			if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
+			if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
+			if isfield(structmd,'isdiagnostic'), md.transient.isstressbalance=structmd.isdiagnostic; end
+			if isfield(structmd,'isprognostic'), md.transient.ismasstransport=structmd.isprognostic; end
+			if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
+			if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
+			if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
+			if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
+			if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
+			if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
+			if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
+			if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
+			if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
+			if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
+			if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
+			if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
+			if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
+			if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
+			if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
+			if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
+			if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
+			if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
+			if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
+			if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
+			if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
+			if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
+			if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
+			if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
+			if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
+			if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
+			if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
+			if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
+			if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
+			if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
+			if isfield(structmd,'long'), md.mesh.long=structmd.long; end
+			if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
+			if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
+			if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
+			if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
+			if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
+			if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
+			if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
+			if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
+			if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
+			if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
+			if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
+			if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
+			if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
+			if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
+			if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
+			if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
+			if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
+			if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
+			if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
+			if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
+			if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
+			if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
+			if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
+			if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
+			if isfield(structmd,'edges'), 
+				md.mesh.edges=structmd.edges; 
+				md.mesh.edges(isnan(md.mesh.edges))=-1;
+			end
+			if isfield(structmd,'y'), md.mesh.y=structmd.y; end
+			if isfield(structmd,'x'), md.mesh.x=structmd.x; end
+			if isfield(structmd,'z'), md.mesh.z=structmd.z; end
+			if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
+			if isfield(structmd,'diagnostic_ref'), md.stressbalance.referential=structmd.diagnostic_ref; end
+			if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
+			if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
+
+			%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 isfield(structmd,'spcvelocity'), 
+				md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(structmd.spcvelocity(:,1)); md.stressbalance.spcvx(pos)=structmd.spcvelocity(pos,4); 
+				pos=find(structmd.spcvelocity(:,2)); md.stressbalance.spcvy(pos)=structmd.spcvelocity(pos,5); 
+				pos=find(structmd.spcvelocity(:,3)); md.stressbalance.spcvz(pos)=structmd.spcvelocity(pos,6); 
+			end
+			if isfield(structmd,'spcvx'), 
+				md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvx)); md.stressbalance.spcvx(pos)=structmd.spcvx(pos); 
+			end
+			if isfield(structmd,'spcvy'),
+				md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvy)); md.stressbalance.spcvy(pos)=structmd.spcvy(pos);     
+			end
+			if isfield(structmd,'spcvz'),
+				md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvz)); md.stressbalance.spcvz(pos)=structmd.spcvz(pos);     
+			end
+			if isfield(structmd,'pressureload'),
+				if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
+					pos=find(structmd.pressureload(:,end)==120); md.stressbalance.icefront(pos,end)=0;
+					pos=find(structmd.pressureload(:,end)==118); md.stressbalance.icefront(pos,end)=1;
+					pos=find(structmd.pressureload(:,end)==119); md.stressbalance.icefront(pos,end)=2;
+				end
+			end
+			if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
+				pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
+				pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
+				pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
+				pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
+				pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
+				pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
+				pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
+				pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
+			end
+			if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
+				pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
+				pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
+				pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
+				pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
+				pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
+				pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
+				pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
+				pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
+			end
+			if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
+				if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
+				if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
+				if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
+			end
+			if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
+				if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
+				if (structmd.groundingline_migration==273), md.groundingline.migration='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.masstransport.stabilization=1;
+					md.balancethickness.stabilization=1;
+			end
+			if isnumeric(md.masstransport.hydrostatic_adjustment)
+				if md.masstransport.hydrostatic_adjustment==269,
+					md.masstransport.hydrostatic_adjustment='Incremental';
+				else
+					md.masstransport.hydrostatic_adjustment='Absolute';
+				end
+			end
+
+			%New fields
+			if ~isfield(structmd,'upperelements');
+				md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
+				md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
+			end
+			if ~isfield(structmd,'lowerelements');
+				md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
+				md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
+			end
+			if ~isfield(structmd,'diagnostic_ref');
+				md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+			end
+			if ~isfield(structmd,'loadingforce');
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+
+			%2013 August 9
+			if isfield(structmd,'prognostic') & isa(structmd.prognostic,'prognostic'),
+				disp('Recovering old prognostic class');
+				md.masstransport=masstransport(structmd.prognostic);
+			end
+			%2013 August 9
+			if isfield(structmd,'diagnostic') & (isa(structmd.diagnostic,'diagnostic') || isa(structmd.diagnostic,'stressbalance')),
+				disp('Recovering old diagnostic class');
+				md.stressbalance=stressbalance(structmd.diagnostic);
+			end
+		end% }}}
+		function md = setdefaultparameters(md) % {{{
+
+			%initialize subclasses
+			md.mesh             = mesh();
+			md.mask             = mask();
+			md.constants        = constants();
+			md.geometry         = geometry();
+			md.initialization   = initialization();
+			md.surfaceforcings  = surfaceforcings();
+			md.basalforcings    = basalforcings();
+			md.friction         = friction();
+			md.rifts            = rifts();
+			md.timestepping     = timestepping();
+			md.groundingline    = groundingline();
+			md.materials        = matice();
+			md.damage           = damage();
+			md.flowequation     = flowequation();
+			md.debug            = debug();
+			md.verbose          = verbose();
+			md.settings         = settings();
+			md.toolkits         = toolkits();
+			md.cluster          = generic();
+			md.balancethickness = balancethickness();
+			md.stressbalance       = stressbalance();
+			md.hydrology        = hydrologyshreve();
+			md.masstransport       = masstransport();
+			md.thermal          = thermal();
+			md.steadystate      = steadystate();
+			md.transient        = transient();
+			md.gia              = gia();
+			md.autodiff         = autodiff();
+			md.flaim            = flaim();
+			md.inversion        = inversion();
+			md.qmu              = qmu();
+			md.radaroverlay     = radaroverlay();
+			md.results          = struct();
+			md.outputdefinition = outputdefinition();
+			md.miscellaneous    = miscellaneous();
+			md.private          = private();
+		end
+		%}}}
+		function disp(obj) % {{{
+			disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
+			disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
+			disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
+			disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
+			disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
+			disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
+			disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
+			disp(sprintf('%19s: %-22s -- %s','damage'          ,['[1x1 ' class(obj.damage) ']'],'damage propagation laws'));
+			disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
+			disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
+			disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
+			disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
+			disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
+			disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
+			disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
+			disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
+			disp(sprintf('%19s: %-22s -- %s','toolkits'          ,['[1x1 ' class(obj.toolkits) ']'],'PETSc options for each solution'));
+			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
+			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
+			disp(sprintf('%19s: %-22s -- %s','stressbalance'      ,['[1x1 ' class(obj.stressbalance) ']'],'parameters for stressbalance solution'));
+			disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
+			disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
+			disp(sprintf('%19s: %-22s -- %s','masstransport'      ,['[1x1 ' class(obj.masstransport) ']'],'parameters for masstransport solution'));
+			disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
+			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
+			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
+			disp(sprintf('%19s: %-22s -- %s','gia'       ,['[1x1 ' class(obj.gia) ']'],'parameters for gia solution'));
+			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
+			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
+			disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
+			disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
+			disp(sprintf('%19s: %-22s -- %s','outputdefinition',['[1x1 ' class(obj.outputdefinition) ']'],'output definition'));
+			disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
+			disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
+			disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
+		end % }}}
+		function memory(obj) % {{{
+
+		disp(sprintf('\nMemory imprint:\n'));
+
+		fields=properties('model');
+		mem=0;
+
+		for i=1:length(fields),
+			field=obj.(fields{i});
+			s=whos('field'); 
+			mem=mem+s.bytes/1e6;
+			disp(sprintf('%19s: %6.2f Mb',fields{i},s.bytes/1e6));
+		end
+		disp(sprintf('%19s--%10s','--------------','--------------'));
+		disp(sprintf('%19s: %g Mb','Total',mem));
+		end % }}}
+		function netcdf(obj,filename) % {{{
+		%NETCDF - save model as netcdf
+		%
+		%   Usage:
+		%      netcdf(md,filename)
+		%
+		%   Example:
+		%      netcdf(md,'model.nc');
+
+		disp('Saving model as NetCDF');
+		%1. Create NetCDF file
+		ncid=netcdf.create(filename,'CLOBBER');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Conventions','CF-1.4');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['ISSM model (' obj.miscellaneous.name ')']);
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Author',getenv('USER'));
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',datestr(now));
+
+		%Preallocate variable id, needed to write variables in netcdf file
+		var_id=zeros(1000,1);%preallocate
+
+		for step=1:2,
+			counter=0;
+			[var_id,counter]=structtonc(ncid,'md',obj,0,var_id,counter,step);
+			if step==1, netcdf.endDef(ncid); end
+		end
+
+		if counter>1000,
+			warning(['preallocation of var_id need to be updated from ' num2str(1000) ' to ' num2str(counter)]);
+		end
+
+		netcdf.close(ncid)
+		end % }}}
+		function xylim(obj) % {{{
+
+			xlim([min(obj.mesh.x) max(obj.mesh.x)]);
+			ylim([min(obj.mesh.y) max(obj.mesh.y)])
+		end % }}}
+		function md=upload(md) % {{{
+		%the goal of this routine is to upload the model onto a server, and to empty it.
+		%So first, save the model with a unique name and upload the file to the server: 
+		random_part=fix(rand(1)*10000);
+		id=[md.miscellaneous.name '-' regexprep(datestr(now),'[^\w'']','') '-' num2str(random_part)  '-' getenv('USER') '-' oshostname() '.upload']; 
+		eval(['save ' id ' md']);
+
+		%Now, upload the file: 
+		issmscpout(md.settings.upload_server,md.settings.upload_path,md.settings.upload_login,md.settings.upload_port,{id},1);
+
+		%Now, empty this model of everything except settings, and record name of file we just uploaded!
+		settings_back=md.settings;
+		md=model();
+		md.settings=settings_back;
+		md.settings.upload_filename=id;
+
+		%get locally rid of file that was uploaded
+		eval(['delete ' id]);
+
+		end % }}}
+		function md=download(md) % {{{
+
+		%the goal of this routine is to download the internals of the current model from a server, because 
+		%this model is empty, except for the settings which tell us where to go and find this model!
+
+		%Download the file: 
+		issmscpin(md.settings.upload_server, md.settings.upload_login, md.settings.upload_port, md.settings.upload_path, {md.settings.upload_filename});
+
+		name=md.settings.upload_filename;
+
+		%Now, load this model: 
+		md=loadmodel(md.settings.upload_filename);
+
+		%get locally rid of file that was downloaded
+		eval(['delete ' name]);
+
+		end % }}}
+	end
+ end
Index: /issm/trunk/src/m/classes/model.py
===================================================================
--- /issm/trunk/src/m/classes/model.py	(revision 16560)
+++ /issm/trunk/src/m/classes/model.py	(revision 16560)
@@ -0,0 +1,681 @@
+#module imports {{{
+import numpy
+import copy
+import sys
+from mesh import mesh
+from mask import mask
+from geometry import geometry
+from constants import constants
+from surfaceforcings import surfaceforcings
+from basalforcings import basalforcings
+from matice import matice
+from damage import damage
+from friction import friction
+from flowequation import flowequation
+from timestepping import timestepping
+from initialization import initialization
+from rifts import rifts
+from debug import debug
+from verbose import verbose
+from settings import settings
+from toolkits import toolkits
+from generic import generic
+from balancethickness import balancethickness
+from stressbalance import stressbalance
+from groundingline import groundingline
+from hydrologyshreve import hydrologyshreve
+from masstransport import masstransport
+from thermal import thermal
+from steadystate import steadystate
+from transient import transient
+from gia import gia
+from autodiff import autodiff
+from flaim import flaim
+from inversion import inversion
+from outputdefinition import outputdefinition
+from qmu import qmu
+from results import results
+from radaroverlay import radaroverlay
+from miscellaneous import miscellaneous
+from private import private
+from EnumDefinitions import *
+from mumpsoptions import *
+from iluasmoptions import *
+from project3d import *
+from FlagElements import *
+from NodeConnectivity import *
+from ElementConnectivity import *
+from contourenvelope import *
+from PythonFuncs import *
+#}}}
+
+class model(object):
+	#properties
+	def __init__(self):#{{{
+		self.mesh             = mesh()
+		self.mask             = mask()
+		self.geometry         = geometry()
+		self.constants        = constants()
+		self.surfaceforcings  = surfaceforcings()
+		self.basalforcings    = basalforcings()
+		self.materials        = matice()
+		self.damage           = damage()
+		self.friction         = friction()
+		self.flowequation     = flowequation()
+		self.timestepping     = timestepping()
+		self.initialization   = initialization()
+		self.rifts            = rifts()
+
+		self.debug            = debug()
+		self.verbose          = verbose()
+		self.settings         = settings()
+		self.toolkits         = toolkits()
+		self.cluster          = generic()
+
+		self.balancethickness = balancethickness()
+		self.stressbalance       = stressbalance()
+		self.groundingline    = groundingline()
+		self.hydrology        = hydrologyshreve()
+		self.masstransport       = masstransport()
+		self.thermal          = thermal()
+		self.steadystate      = steadystate()
+		self.transient        = transient()
+		self.gia              = gia()
+
+		self.autodiff         = autodiff()
+		self.flaim            = flaim()
+		self.inversion        = inversion()
+		self.qmu              = qmu()
+
+		self.results          = results()
+		self.outputdefinition = outputdefinition()
+		self.radaroverlay     = radaroverlay()
+		self.miscellaneous    = miscellaneous()
+		self.private          = private()
+		#}}}
+	def properties(self):    # {{{
+		# ordered list of properties since vars(self) is random
+		return ['mesh',\
+		        'mask',\
+		        'geometry',\
+		        'constants',\
+		        'surfaceforcings',\
+		        'basalforcings',\
+		        'materials',\
+		        'damage',\
+		        'friction',\
+		        'flowequation',\
+		        'timestepping',\
+		        'initialization',\
+		        'rifts',\
+		        'debug',\
+		        'verbose',\
+		        'settings',\
+		        'toolkits',\
+		        'cluster',\
+		        'balancethickness',\
+		        'stressbalance',\
+		        'groundingline',\
+		        'hydrology',\
+		        'masstransport',\
+		        'thermal',\
+		        'steadystate',\
+		        'transient',\
+				  'gia',\
+		        'autodiff',\
+		        'flaim',\
+		        'inversion',\
+		        'qmu',\
+		        'outputdefinition',\
+		        'results',\
+		        'radaroverlay',\
+		        'miscellaneous',\
+		        'private']
+	# }}}
+	def __repr__(obj): #{{{
+		#print "Here %s the number: %d" % ("is", 37)
+		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("surfaceforcings","[%s,%s]" % ("1x1",obj.surfaceforcings.__class__.__name__),"surface forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("damage","[%s,%s]" % ("1x1",obj.damage.__class__.__name__),"damage propagation laws"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("stressbalance","[%s,%s]" % ("1x1",obj.stressbalance.__class__.__name__),"parameters for stressbalance solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("masstransport","[%s,%s]" % ("1x1",obj.masstransport.__class__.__name__),"parameters for masstransport solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("outputdefinition","[%s,%s]" % ("1x1",obj.outputdefinition.__class__.__name__),"output definition"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
+		return string
+	# }}}
+	def checkmessage(self,string):    # {{{
+		print ("model not consistent: %s" % string)
+		self.private.isconsistent=False
+		return self
+	# }}}
+	def extract(md,area):    # {{{
+		"""
+		extract - extract a model according to an Argus contour or flag list
+
+		   This routine extracts a submodel from a bigger model with respect to a given contour
+		   md must be followed by the corresponding exp file or flags list
+		   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+		   If user wants every element outside the domain to be 
+		   extract2d, add '~' to the name of the domain file (ex: '~HO.exp');
+		   an empty string '' will be considered as an empty domain
+		   a string 'all' will be considered as the entire domain
+
+		   Usage:
+		      md2=extract(md,area);
+
+		   Examples:
+		      md2=extract(md,'Domain.exp');
+
+		   See also: EXTRUDE, COLLAPSE
+		"""
+
+		#copy model
+		md1=copy.deepcopy(md)
+
+		#get elements that are inside area
+		flag_elem=FlagElements(md1,area)
+		if not numpy.any(flag_elem):
+			raise RuntimeError("extracted model is empty")
+
+		#kick out all elements with 3 dirichlets
+		spc_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
+		spc_node=numpy.unique(md1.mesh.elements[spc_elem,:])-1
+		flag=numpy.ones(md1.mesh.numberofvertices)
+		flag[spc_node]=0
+		pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements-1],axis=1)))[0]
+		flag_elem[pos]=0
+
+		#extracted elements and nodes lists
+		pos_elem=numpy.nonzero(flag_elem)[0]
+		pos_node=numpy.unique(md1.mesh.elements[pos_elem,:])-1
+
+		#keep track of some fields
+		numberofvertices1=md1.mesh.numberofvertices
+		numberofelements1=md1.mesh.numberofelements
+		numberofvertices2=numpy.size(pos_node)
+		numberofelements2=numpy.size(pos_elem)
+		flag_node=numpy.zeros(numberofvertices1)
+		flag_node[pos_node]=1
+
+		#Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+		Pelem=numpy.zeros(numberofelements1,int)
+		Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
+		Pnode=numpy.zeros(numberofvertices1,int)
+		Pnode[pos_node]=numpy.arange(1,numberofvertices2+1)
+
+		#renumber the elements (some node won't exist anymore)
+		elements_1=copy.deepcopy(md1.mesh.elements)
+		elements_2=elements_1[pos_elem,:]
+		elements_2[:,0]=Pnode[elements_2[:,0]-1]
+		elements_2[:,1]=Pnode[elements_2[:,1]-1]
+		elements_2[:,2]=Pnode[elements_2[:,2]-1]
+		if md1.mesh.dimension==3:
+			elements_2[:,3]=Pnode[elements_2[:,3]-1]
+			elements_2[:,4]=Pnode[elements_2[:,4]-1]
+			elements_2[:,5]=Pnode[elements_2[:,5]-1]
+
+		#OK, now create the new model!
+
+		#take every field from model
+		md2=copy.deepcopy(md1)
+
+		#automatically modify fields
+
+		#loop over model fields
+		model_fields=vars(md1)
+		for fieldi in model_fields:
+			#get field
+			field=getattr(md1,fieldi)
+			fieldsize=numpy.shape(field)
+			if hasattr(field,'__dict__') and not ismember(fieldi,['results'])[0]:    #recursive call
+				object_fields=vars(field)
+				for fieldj in object_fields:
+					#get field
+					field=getattr(getattr(md1,fieldi),fieldj)
+					fieldsize=numpy.shape(field)
+					if len(fieldsize):
+						#size = number of nodes * n
+						if   fieldsize[0]==numberofvertices1:
+							setattr(getattr(md2,fieldi),fieldj,field[pos_node,:])
+						elif fieldsize[0]==numberofvertices1+1:
+							setattr(getattr(md2,fieldi),fieldj,numpy.vstack((field[pos_node,:],field[-1,:])))
+						#size = number of elements * n
+						elif fieldsize[0]==numberofelements1:
+							setattr(getattr(md2,fieldi),fieldj,field[pos_elem,:])
+			else:
+				if len(fieldsize):
+					#size = number of nodes * n
+					if   fieldsize[0]==numberofvertices1:
+						setattr(md2,fieldi,field[pos_node,:])
+					elif fieldsize[0]==numberofvertices1+1:
+						setattr(md2,fieldi,numpy.hstack((field[pos_node,:],field[-1,:])))
+					#size = number of elements * n
+					elif fieldsize[0]==numberofelements1:
+						setattr(md2,fieldi,field[pos_elem,:])
+
+		#modify some specific fields
+
+		#Mesh
+		md2.mesh.numberofelements=numberofelements2
+		md2.mesh.numberofvertices=numberofvertices2
+		md2.mesh.elements=elements_2
+
+		#mesh.uppervertex mesh.lowervertex
+		if md1.mesh.dimension==3:
+			md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.uppervertex==-1))[0]
+			md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos]-1]
+
+			md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowervertex==-1))[0]
+			md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos]-1]
+
+			md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.upperelements==-1))[0]
+			md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos]-1]
+
+			md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowerelements==-1))[0]
+			md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos]-1]
+
+		#Initial 2d mesh 
+		if md1.mesh.dimension==3:
+			flag_elem_2d=flag_elem[numpy.arange(0,md1.mesh.numberofelements2d)]
+			pos_elem_2d=numpy.nonzero(flag_elem_2d)[0]
+			flag_node_2d=flag_node[numpy.arange(0,md1.mesh.numberofvertices2d)]
+			pos_node_2d=numpy.nonzero(flag_node_2d)[0]
+
+			md2.mesh.numberofelements2d=numpy.size(pos_elem_2d)
+			md2.mesh.numberofvertices2d=numpy.size(pos_node_2d)
+			md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:]
+			md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0]-1]
+			md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1]-1]
+			md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2]-1]
+
+			md2.mesh.x2d=md1.mesh.x[pos_node_2d]
+			md2.mesh.y2d=md1.mesh.y[pos_node_2d]
+
+		#Edges
+		if numpy.ndim(md2.mesh.edges)>1 and numpy.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some NaNs...
+			#renumber first two columns
+			pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
+			md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0]-1]
+			md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1]-1]
+			md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2]-1]
+			md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-1]
+			#remove edges when the 2 vertices are not in the domain.
+			md2.mesh.edges=md2.mesh.edges[numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
+			#Replace all zeros by -1 in the last two columns
+			pos=numpy.nonzero(md2.mesh.edges[:,2]==0)[0]
+			md2.mesh.edges[pos,2]=-1
+			pos=numpy.nonzero(md2.mesh.edges[:,3]==0)[0]
+			md2.mesh.edges[pos,3]=-1
+			#Invert -1 on the third column with last column (Also invert first two columns!!)
+			pos=numpy.nonzero(md2.mesh.edges[:,2]==-1)[0]
+			md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3]
+			md2.mesh.edges[pos,3]=-1
+			values=md2.mesh.edges[pos,1]
+			md2.mesh.edges[pos,1]=md2.mesh.edges[pos,0]
+			md2.mesh.edges[pos,0]=values
+			#Finally remove edges that do not belong to any element
+			pos=numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
+			md2.mesh.edges=numpy.delete(md2.mesh.edges,pos,axis=0)
+
+		#Penalties
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.stressbalance.vertex_pairing))):
+			for i in xrange(numpy.size(md1.stressbalance.vertex_pairing,axis=0)):
+				md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]]
+			md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[numpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):
+			for i in xrange(numpy.size(md1.masstransport.vertex_pairing,axis=0)):
+				md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]]
+			md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
+
+		#recreate segments
+		if md1.mesh.dimension==2:
+			[md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
+			[md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
+			md2.mesh.segments=contourenvelope(md2)
+			md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2,bool)
+			md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True
+		else:
+			#First do the connectivity for the contourenvelope in 2d
+			[md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)
+			[md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)
+			md2.mesh.segments=contourenvelope(md2)
+			md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
+			md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True
+			md2.mesh.vertexonboundary=numpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
+			#Then do it for 3d as usual
+			[md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
+			[md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
+
+		#Boundary conditions: Dirichlets on new boundary
+		#Catch the elements that have not been extracted
+		orphans_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
+		orphans_node=numpy.unique(md1.mesh.elements[orphans_elem,:])-1
+		#Figure out which node are on the boundary between md2 and md1
+		nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
+		nodestoflag2=Pnode[nodestoflag1].astype(int)-1
+		if numpy.size(md1.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:
+			if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
+				md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
+				md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
+			else:
+				md2.stressbalance.spcvx[nodestoflag2]=float('NaN')
+				md2.stressbalance.spcvy[nodestoflag2]=float('NaN')
+				print "\n!! extract warning: spc values should be checked !!\n\n"
+			#put 0 for vz
+			md2.stressbalance.spcvz[nodestoflag2]=0
+		if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
+			md2.thermal.spctemperature[nodestoflag2,0]=1
+
+		#Results fields
+		if md1.results:
+			md2.results=results()
+			for solutionfield,field in md1.results.__dict__.iteritems():
+				if   isinstance(field,list):
+					setattr(md2.results,solutionfield,[])
+					#get time step
+					for i,fieldi in enumerate(field):
+						if isinstance(fieldi,results) and fieldi:
+							getattr(md2.results,solutionfield).append(results())
+							fieldr=getattr(md2.results,solutionfield)[i]
+							#get subfields
+							for solutionsubfield,subfield in fieldi.__dict__.iteritems():
+								if   numpy.size(subfield)==numberofvertices1:
+									setattr(fieldr,solutionsubfield,subfield[pos_node])
+								elif numpy.size(subfield)==numberofelements1:
+									setattr(fieldr,solutionsubfield,subfield[pos_elem])
+								else:
+									setattr(fieldr,solutionsubfield,subfield)
+						else:
+							getattr(md2.results,solutionfield).append(None)
+				elif isinstance(field,results):
+					setattr(md2.results,solutionfield,results())
+					if isinstance(field,results) and field:
+						fieldr=getattr(md2.results,solutionfield)
+						#get subfields
+						for solutionsubfield,subfield in field.__dict__.iteritems():
+							if   numpy.size(subfield)==numberofvertices1:
+								setattr(fieldr,solutionsubfield,subfield[pos_node])
+							elif numpy.size(subfield)==numberofelements1:
+								setattr(fieldr,solutionsubfield,subfield[pos_elem])
+							else:
+								setattr(fieldr,solutionsubfield,subfield)
+
+		#Keep track of pos_node and pos_elem
+		md2.mesh.extractedvertices=pos_node+1
+		md2.mesh.extractedelements=pos_elem+1
+
+		return md2
+	# }}}
+	def extrude(md,*args):    # {{{
+		"""
+		EXTRUDE - vertically extrude a 2d mesh
+
+		   vertically extrude a 2d mesh and create corresponding 3d mesh.
+		   The vertical distribution can:
+		    - follow a polynomial law
+		    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+		    - be discribed by a list of coefficients (between 0 and 1)
+ 
+
+		   Usage:
+		      md=extrude(md,numlayers,extrusionexponent);
+		      md=extrude(md,numlayers,lowerexponent,upperexponent);
+		      md=extrude(md,listofcoefficients);
+
+		   Example:
+		      md=extrude(md,8,3);
+		      md=extrude(md,8,3,2);
+		      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
+
+		   See also: MODELEXTRACT, COLLAPSE
+		"""
+
+		#some checks on list of arguments
+		if len(args)>3 or len(args)<1:
+			raise RuntimeError("extrude error message")
+
+		#Extrude the mesh
+		if   len(args)==1:    #list of coefficients
+			clist=args[0]
+			if any(clist<0) or any(clist>1):
+				raise TypeError("extrusioncoefficients must be between 0 and 1")
+			clist.extend([0.,1.])
+			clist.sort()
+			extrusionlist=list(set(clist))
+			numlayers=len(extrusionlist)
+
+		elif len(args)==2:    #one polynomial law
+			if args[1]<=0:
+				raise TypeError("extrusionexponent must be >=0")
+			numlayers=args[0]
+			extrusionlist=(numpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
+
+		elif len(args)==3:    #two polynomial laws
+			numlayers=args[0]
+			lowerexp=args[1]
+			upperexp=args[2]
+
+			if args[1]<=0 or args[2]<=0:
+				raise TypeError("lower and upper extrusionexponents must be >=0")
+
+			lowerextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
+			upperextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
+			extrusionlist=numpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
+
+		if numlayers<2:
+			raise TypeError("number of layers should be at least 2")
+		if md.mesh.dimension==3:
+			raise TypeError("Cannot extrude a 3d mesh (extrude cannot be called more than once)")
+
+		#Initialize with the 2d mesh
+		x3d=numpy.empty((0))
+		y3d=numpy.empty((0))
+		z3d=numpy.empty((0))    #the lower node is on the bed
+		thickness3d=md.geometry.thickness    #thickness and bed for these nodes
+		bed3d=md.geometry.bed
+
+		#Create the new layers
+		for i in xrange(numlayers):
+			x3d=numpy.concatenate((x3d,md.mesh.x))
+			y3d=numpy.concatenate((y3d,md.mesh.y))
+			#nodes are distributed between bed and surface accordingly to the given exponent
+			z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
+		number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Extrude elements 
+		elements3d=numpy.empty((0,6),int)
+		for i in xrange(numlayers-1):
+			elements3d=numpy.vstack((elements3d,numpy.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices))))    #Create the elements of the 3d mesh for the non extruded part
+		number_el3d=numpy.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Keep a trace of lower and upper nodes
+		mesh.lowervertex=-1*numpy.ones(number_nodes3d,int)
+		mesh.uppervertex=-1*numpy.ones(number_nodes3d,int)
+		mesh.lowervertex[md.mesh.numberofvertices:]=numpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
+		mesh.uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=numpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
+		md.mesh.lowervertex=mesh.lowervertex
+		md.mesh.uppervertex=mesh.uppervertex
+
+		#same for lower and upper elements
+		mesh.lowerelements=-1*numpy.ones(number_el3d,int)
+		mesh.upperelements=-1*numpy.ones(number_el3d,int)
+		mesh.lowerelements[md.mesh.numberofelements:]=numpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
+		mesh.upperelements[:(numlayers-2)*md.mesh.numberofelements]=numpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
+		md.mesh.lowerelements=mesh.lowerelements
+		md.mesh.upperelements=mesh.upperelements
+
+		#Save old mesh 
+		md.mesh.x2d=md.mesh.x
+		md.mesh.y2d=md.mesh.y
+		md.mesh.elements2d=md.mesh.elements
+		md.mesh.numberofelements2d=md.mesh.numberofelements
+		md.mesh.numberofvertices2d=md.mesh.numberofvertices
+
+		#Update mesh type
+		md.mesh.dimension=3
+
+		#Build global 3d mesh 
+		md.mesh.elements=elements3d
+		md.mesh.x=x3d
+		md.mesh.y=y3d
+		md.mesh.z=z3d
+		md.mesh.numberofelements=number_el3d
+		md.mesh.numberofvertices=number_nodes3d
+		md.mesh.numberoflayers=numlayers
+
+		#Ok, now deal with the other fields from the 2d mesh:
+
+		#lat long
+		md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node')
+		md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node')
+
+		#drag coefficient is limited to nodes that are on the bedrock.
+		md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1)
+
+		#p and q (same deal, except for element that are on the bedrock: )
+		md.friction.p=project3d(md,'vector',md.friction.p,'type','element')
+		md.friction.q=project3d(md,'vector',md.friction.q,'type','element')
+
+		#observations
+		md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node')
+		md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node')
+		md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node')
+		md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node')
+		md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node')
+		md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node')
+		md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node')
+
+		#results
+		if not numpy.any(numpy.isnan(md.initialization.vx)):
+			md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vy)):
+			md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vz)):
+			md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vel)):
+			md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.temperature)):
+			md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.waterfraction)):
+			md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node')
+
+		#bedinfo and surface info
+		md.mesh.elementonbed=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d,bool),'type','element','layer',1)
+		md.mesh.elementonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d,bool),'type','element','layer',md.mesh.numberoflayers-1)
+		md.mesh.vertexonbed=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
+		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
+
+		#elementstype
+		if not numpy.any(numpy.isnan(md.flowequation.element_equation)):
+			oldelements_type=md.flowequation.element_equation
+			md.flowequation.element_equation=numpy.zeros(number_el3d,int)
+			md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element')
+
+		#verticestype
+		if not numpy.any(numpy.isnan(md.flowequation.vertex_equation)):
+			oldvertices_type=md.flowequation.vertex_equation
+			md.flowequation.vertex_equation=numpy.zeros(number_nodes3d,int)
+			md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node')
+
+		md.flowequation.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node')
+		md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node')
+		md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node')
+
+		#boundary conditions
+		md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node')
+		md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node')
+		md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node')
+		md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',float('NaN'))
+		md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node')
+		md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node')
+		md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node')
+		md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node')
+		md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node')
+
+		#connectivity
+		md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
+		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxint-1
+		for i in xrange(1,numlayers-1):
+			md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
+				=md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
+		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
+
+		#materials
+		md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node')
+		md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element')
+
+		#damage
+		md.damage.D=project3d(md,'vector',md.damage.D,'type','node')
+
+		#parameters
+		md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node')
+		md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node')
+		md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node')
+		md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node')
+		md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node')
+		md.geometry.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.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node')
+		md.mask.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.cost_functions_coefficients)):
+			md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+		if not numpy.any(numpy.isnan(md.inversion.min_parameters)):
+			md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.max_parameters)):
+			md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.qmu.partition)):
+			md.qmu.partition=project3d(md,'vector',numpy.transpose(md.qmu.partition),'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node')
+
+		#Put lithostatic pressure if there is an existing pressure
+		if not numpy.any(numpy.isnan(md.initialization.pressure)):
+			md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
+
+		#special for thermal modeling:
+		md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1)
+		if not numpy.any(numpy.isnan(md.basalforcings.geothermalflux)):
+			md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
+
+		#increase connectivity if less than 25:
+		if md.mesh.average_vertex_connectivity<=25:
+			md.mesh.average_vertex_connectivity=100
+
+		return md
+		# }}}
Index: /issm/trunk/src/m/classes/outputdefinition.m
===================================================================
--- /issm/trunk/src/m/classes/outputdefinition.m	(revision 16560)
+++ /issm/trunk/src/m/classes/outputdefinition.m	(revision 16560)
@@ -0,0 +1,52 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      outputdefinition=outputdefinition();
+
+classdef outputdefinition
+	properties (SetAccess=public) 
+		definitions                 = {};
+	end
+	methods
+		function obj = outputdefinition(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			obj.definitions={};
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'outputdefinition.definitions','cell',1);
+
+			for i=1:length(obj.definitions),
+				md=checkconsistency(obj.definitions{i},md,solution,analyses);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   outputdefinition:'));
+			fielddisplay(obj,'definitions','list of potential outputs that can be requested, but which need additional data to be defined');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+		enums=zeros(length(obj.definitions),1);
+		for i=1:length(obj.definitions),
+			obj.definitions{i}.marshall(md,fid);
+			classdefinition=class(obj.definitions{i});
+			classdefinition(1)=upper(classdefinition(1)); %so it matches our enums definitions.
+			enums(i)=StringToEnum(classdefinition);
+		end
+		enums=unique(enums);
+		
+		WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/outputdefinition.py
===================================================================
--- /issm/trunk/src/m/classes/outputdefinition.py	(revision 16560)
+++ /issm/trunk/src/m/classes/outputdefinition.py	(revision 16560)
@@ -0,0 +1,49 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+import numpy as npy
+
+class outputdefinition(object):
+	"""
+	OUTPUTDEFINITION class definition
+
+	   Usage:
+	      outputdefinition=outputdefinition();
+	"""
+
+	def __init__(self): # {{{
+		self.definitions                   = []
+		#}}}
+	def __repr__(self): # {{{
+		string="   Outputdefinitions:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"definitions","list of potential outputs that can be requested, but which need additional data to be defined"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		md = checkfield(md,'outputdefinition.definitions','cell',1)
+		for definition in self.definitions:
+			definition.checkconsistency(md,solution,analyses);
+
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		
+		enums=npy.zeros(len(self.definitions),)
+		
+		for i in range(len(self.definitions)):
+			self.definitions[i].marshall(md,fid);
+			classdefinition=self.definitions[i].__class__.__name__
+			classdefinition=classdefinition[0].upper()+classdefinition[1:]
+			enums[i]=StringToEnum(classdefinition)[0]
+		
+		enums=npy.unique(enums);
+		
+		WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1);
+	# }}}
Index: sm/trunk/src/m/classes/planetmesh.m
===================================================================
--- /issm/trunk/src/m/classes/planetmesh.m	(revision 16559)
+++ 	(revision )
@@ -1,123 +1,0 @@
-%PLANETMESH class definition
-%
-%   Usage:
-%      planetmesh=planetmesh();
-
-classdef planetmesh
-	properties (SetAccess=public) 
-		x                           = NaN;
-		y                           = NaN;
-		z                           = NaN;
-		r                           = NaN;
-		theta                       = NaN;
-		phi                         = NaN
-		elements                    = NaN
-		dimension                   = 0;
-		numberoflayers              = 0;
-		numberofelements            = 0;
-		numberofvertices            = 0;
-
-		vertexconnectivity          = NaN
-		elementconnectivity         = NaN
-		average_vertex_connectivity = 0;
-	end
-	methods
-		function obj = planetmesh(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			%the connectivity is the avergaded number of nodes linked to a
-			%given node through an edge. This connectivity is used to initially
-			%allocate memory to the stiffness matrix. A value of 16 seems to
-			%give a good memory/time ration. This value can be checked in
-			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-
-			md = checkfield(md,'planetmesh.x','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.y','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.z','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.r','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.theta','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.phi','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
-			md = checkfield(md,'planetmesh.elements','NaN',1,'>',0,'values',1:md.planetmesh.numberofvertices);
-			if(md.planetmesh.dimension==2),
-				md = checkfield(md,'planetmesh.elements','size',[md.planetmesh.numberofelements 3]);
-			else
-				md = checkfield(md,'planetmesh.elements','size',[md.planetmesh.numberofelements 6]);
-			end
-			if any(~ismember(1:md.planetmesh.numberofvertices,sort(unique(md.planetmesh.elements(:)))));
-				md = checkmessage(md,'orphan nodes have been found. Check the planetmesh outline');
-			end
-			md = checkfield(md,'planetmesh.dimension','values',[2 3]);
-			md = checkfield(md,'planetmesh.numberoflayers','>=',0);
-			md = checkfield(md,'planetmesh.numberofelements','>',0);
-			md = checkfield(md,'planetmesh.numberofvertices','>',0);
-			if (md.planetmesh.dimension==2),
-				md = checkfield(md,'planetmesh.average_vertex_connectivity','>=',9,'message','''planetmesh.average_vertex_connectivity'' should be at least 9 in 2d');
-			else
-				md = checkfield(md,'planetmesh.average_vertex_connectivity','>=',24,'message','''planetmesh.average_vertex_connectivity'' should be at least 24 in 3d');
-			end
-			md = checkfield(md,'planetmesh.elementconnectivity','size',[md.planetmesh.numberofelements 3],'NaN',1);
-
-			%Solution specific checks
-			switch(solution),
-				case MasstransportSolutionEnum(),
-					if md.masstransport.stabilization==3,
-						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
-					end
-				case TransientSolutionEnum(),
-					if md.transient.ismasstransport & md.masstransport.stabilization==3,
-						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
-					end
-				case ThermalSolutionEnum(),
-					md = checkfield(md,'planetmesh.dimension','values',3,'message','thermal solution only supported on 3d planetmeshes');
-			end
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   Mesh:')); 
-
-			disp(sprintf('\n      Elements and vertices:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'z','vertices z coordinate [m]');
-			fielddisplay(obj,'r','vertices r coordinate [m]');
-			fielddisplay(obj,'theta','vertices theta coordinate [degrees]');
-			fielddisplay(obj,'phi','vertices phi coordinate [degrees]');
-
-			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'dimension','planetmesh dimension (2d or 3d)');
-			fielddisplay(obj,'numberoflayers','number of extrusion layers');
-
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','phi','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','dimension','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
-		end % }}}
-	end
-end
Index: /issm/trunk/src/m/classes/plotoptions.m
===================================================================
--- /issm/trunk/src/m/classes/plotoptions.m	(revision 16559)
+++ /issm/trunk/src/m/classes/plotoptions.m	(revision 16560)
@@ -45,4 +45,10 @@
 			 %check length of input
 			 if mod((nargin-1),2),
+				 for i=1:2:(nargin-1)
+					 if ~ischar(varargin{i}),
+						 disp(['Last valid option: ' varargin{i-2} ]);
+						 break;
+					 end
+				 end
 				 error('Invalid parameter/value pair arguments')
 			 end
Index: /issm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 16559)
+++ /issm/trunk/src/m/classes/settings.m	(revision 16560)
@@ -8,5 +8,4 @@
 		io_gather           = 0;
 		lowmem              = 0;
-		results_as_patches  = 0;
 		output_frequency    = 0;
 		waitonlock          = 0;
@@ -38,7 +37,4 @@
 			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
@@ -55,5 +51,4 @@
 			md = checkfield(md,'settings.io_gather','numel',[1],'values',[0 1]);
 			md = checkfield(md,'settings.lowmem','numel',[1],'values',[0 1]);
-			md = checkfield(md,'settings.results_as_patches','numel',[1],'values',[0 1]);
 			md = checkfield(md,'settings.output_frequency','numel',[1],'>=',1);
 			md = checkfield(md,'settings.waitonlock','numel',[1]);
@@ -65,5 +60,4 @@
 			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 (NaN to deactivate)');
@@ -78,5 +72,4 @@
 			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');
 			if obj.waitonlock>0,
Index: /issm/trunk/src/m/classes/settings.py
===================================================================
--- /issm/trunk/src/m/classes/settings.py	(revision 16559)
+++ /issm/trunk/src/m/classes/settings.py	(revision 16560)
@@ -15,5 +15,4 @@
 		self.io_gather           = 0
 		self.lowmem              = 0
-		self.results_as_patches  = 0
 		self.output_frequency    = 0
 		self.waitonlock          = 0
@@ -28,5 +27,4 @@
 		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
 		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(self,"results_as_patches","provide results as patches for each element (0 or 1)"))
 		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
 		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
@@ -44,7 +42,4 @@
 		self.output_frequency=1
 
-		#do not use patches by default (difficult to plot)
-		self.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
@@ -58,5 +53,4 @@
 		md = checkfield(md,'settings.io_gather','numel',[1],'values',[0,1])
 		md = checkfield(md,'settings.lowmem','numel',[1],'values',[0,1])
-		md = checkfield(md,'settings.results_as_patches','numel',[1],'values',[0,1])
 		md = checkfield(md,'settings.output_frequency','numel',[1],'>=',1)
 		md = checkfield(md,'settings.waitonlock','numel',[1])
@@ -67,5 +61,4 @@
 		WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','results_as_patches','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','output_frequency','format','Integer')
 		if self.waitonlock>0:
Index: /issm/trunk/src/m/classes/snowpack.m
===================================================================
--- /issm/trunk/src/m/classes/snowpack.m	(revision 16559)
+++ /issm/trunk/src/m/classes/snowpack.m	(revision 16560)
@@ -124,5 +124,5 @@
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
-	
+
 		%snowpack:  %{{{
 		obj.snowpack_meas_tss = 1;
@@ -279,5 +279,4 @@
 			%filters {{{
 			filter_values={'MIN_MAX','RATE_FILTER1','RATE_FILTER2','UNHEATED_RAIN_GAUGE_FILTER','WMO_UNDERCATCH_FILTER','WMO_UNDERCATCH_FILTER-SIMPLIFIED','UNVENTILLATED_TEMPERATURE_SENSOR','ADD_AN_OFFSET'};
-
 
 			md=checkfield(md,'snowpack.filters_ta_filter1','values',{filter_values});
@@ -472,5 +471,5 @@
 			WriteData(fid,'object',obj,'class','snowpack','fieldname','rift_penalty_threshold','format','Integer');
 			WriteData(fid,'object',obj,'class','snowpack','fieldname','referential','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','requested_outputs','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','requested_outputs','format','StringArray');
 			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
 			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
Index: /issm/trunk/src/m/classes/spheremesh.m
===================================================================
--- /issm/trunk/src/m/classes/spheremesh.m	(revision 16560)
+++ /issm/trunk/src/m/classes/spheremesh.m	(revision 16560)
@@ -0,0 +1,123 @@
+%SPHEREMESH class definition
+%
+%   Usage:
+%      spheremesh=spheremesh();
+
+classdef spheremesh
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN;
+		r                           = NaN;
+		theta                       = NaN;
+		phi                         = NaN
+		elements                    = NaN
+		dimension                   = 0;
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+	end
+	methods
+		function obj = spheremesh(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the avergaded number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'spheremesh.x','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.y','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.z','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.r','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.theta','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.phi','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'spheremesh.elements','NaN',1,'>',0,'values',1:md.spheremesh.numberofvertices);
+			if(md.spheremesh.dimension==2),
+				md = checkfield(md,'spheremesh.elements','size',[md.spheremesh.numberofelements 3]);
+			else
+				md = checkfield(md,'spheremesh.elements','size',[md.spheremesh.numberofelements 6]);
+			end
+			if any(~ismember(1:md.spheremesh.numberofvertices,sort(unique(md.spheremesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the spheremesh outline');
+			end
+			md = checkfield(md,'spheremesh.dimension','values',[2 3]);
+			md = checkfield(md,'spheremesh.numberoflayers','>=',0);
+			md = checkfield(md,'spheremesh.numberofelements','>',0);
+			md = checkfield(md,'spheremesh.numberofvertices','>',0);
+			if (md.spheremesh.dimension==2),
+				md = checkfield(md,'spheremesh.average_vertex_connectivity','>=',9,'message','''spheremesh.average_vertex_connectivity'' should be at least 9 in 2d');
+			else
+				md = checkfield(md,'spheremesh.average_vertex_connectivity','>=',24,'message','''spheremesh.average_vertex_connectivity'' should be at least 24 in 3d');
+			end
+			md = checkfield(md,'spheremesh.elementconnectivity','size',[md.spheremesh.numberofelements 3],'NaN',1);
+
+			%Solution specific checks
+			switch(solution),
+				case MasstransportSolutionEnum(),
+					if md.masstransport.stabilization==3,
+						md = checkfield(md,'spheremesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d spheremeshes');
+					end
+				case TransientSolutionEnum(),
+					if md.transient.ismasstransport & md.masstransport.stabilization==3,
+						md = checkfield(md,'spheremesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d spheremeshes');
+					end
+				case ThermalSolutionEnum(),
+					md = checkfield(md,'spheremesh.dimension','values',3,'message','thermal solution only supported on 3d spheremeshes');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(obj,'r','vertices r coordinate [m]');
+			fielddisplay(obj,'theta','vertices theta coordinate [degrees]');
+			fielddisplay(obj,'phi','vertices phi coordinate [degrees]');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'dimension','spheremesh dimension (2d or 3d)');
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','phi','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','dimension','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk/src/m/classes/steadystate.m	(revision 16559)
+++ /issm/trunk/src/m/classes/steadystate.m	(revision 16560)
@@ -8,5 +8,5 @@
 		reltol            = 0;
 		maxiter           = 0;
-		requested_outputs = NaN;
+		requested_outputs = {};
 	end
 	methods
@@ -25,4 +25,12 @@
 			%Relative tolerance for the steadystate convertgence
 			obj.reltol=0.01;
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function list=defaultoutputs(self,md) % {{{
+
+			list =  [md.stressbalance.defaultoutputs(md) md.thermal.defaultoutputs(md)];
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -34,4 +42,5 @@
 				md = checkmessage(md,['for a steadystate computation, timestepping.time_step must be zero.']);
 			end
+			md = checkfield(md,'steadystate.requested_outputs','stringrow',1);
 
 			if isnan(md.stressbalance.reltol),
@@ -50,5 +59,13 @@
 			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);
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum,'format','StringArray');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/steadystate.py
===================================================================
--- /issm/trunk/src/m/classes/steadystate.py	(revision 16559)
+++ /issm/trunk/src/m/classes/steadystate.py	(revision 16560)
@@ -16,5 +16,5 @@
 		self.reltol            = 0
 		self.maxiter           = 0
-		self.requested_outputs = float('NaN')
+		self.requested_outputs = []
 
 		#set defaults
@@ -29,4 +29,9 @@
 		return string
 		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		return md.stressbalance.defaultoutputs(md)+md.thermal.defaultoutputs(md)
+
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -37,4 +42,6 @@
 		self.reltol=0.01
 
+		#default output
+		self.requested_outputs=['default']
 		return self
 	#}}}
@@ -51,4 +58,6 @@
 			md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!")
 
+		md = checkfield(md,'steadystate.requested_outputs','stringrow',1)
+
 		return md
 	# }}}
@@ -56,4 +65,11 @@
 		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
 		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
-		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum(),'format','StringArray')
 	# }}}
Index: /issm/trunk/src/m/classes/stressbalance.m
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.m	(revision 16559)
+++ /issm/trunk/src/m/classes/stressbalance.m	(revision 16560)
@@ -23,5 +23,5 @@
 		referential            = NaN;
 		loadingforce           = NaN;
-		requested_outputs      = NaN;
+		requested_outputs      = {};
 	end
 	methods
@@ -73,4 +73,7 @@
 			 obj.rift_penalty_lock=10;
 
+			 %output default:
+			 obj.requested_outputs={'default'};
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -81,5 +84,5 @@
 			md = checkfield(md,'stressbalance.spcvx','forcing',1);
 			md = checkfield(md,'stressbalance.spcvy','forcing',1);
-			if md.mesh.dimension==3, md = checkfield(md,'stressbalance.spcvz','forcing',1); end
+			md = checkfield(md,'stressbalance.spcvz','forcing',1);
 			md = checkfield(md,'stressbalance.restol','size',[1 1],'>',0,'NaN',1);
 			md = checkfield(md,'stressbalance.reltol','size',[1 1]);
@@ -91,10 +94,8 @@
 			md = checkfield(md,'stressbalance.referential','size',[md.mesh.numberofvertices 6]);
 			md = checkfield(md,'stressbalance.loadingforce','size',[md.mesh.numberofvertices 3]);
-			if ~isempty(md.stressbalance.requested_outputs),
-				md = checkfield(md,'stressbalance.requested_outputs','size',[NaN 1]);
-			end
+			md = checkfield(md,'stressbalance.requested_outputs','stringrow',1);
 
 			%singular solution
-			if ~(any(~isnan(md.stressbalance.spcvx)) & any(~isnan(md.stressbalance.spcvy))),
+			if ~(any(~isnan(md.stressbalance.spcvx)) | any(~isnan(md.stressbalance.spcvy))),
 				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
 			end
@@ -111,5 +112,5 @@
 			end
 			%CHECK THAT NO rotation specified for FS Grounded ice at base
-			if md.mesh.dimension==3 & md.flowequation.isFS,
+			if strcmp(meshtype(md.mesh),'3D') & md.flowequation.isFS,
 				pos=find(md.mask.groundedice_levelset>0. & md.mesh.vertexonbed);
 				if any(~isnan(md.stressbalance.referential(pos,:))),
@@ -118,4 +119,17 @@
 				md = checkfield(md,'stressbalance.FSreconditioning','>',0);
 			end
+		end % }}}
+		function list=defaultoutputs(self,md) % {{{
+
+			if strcmp(meshtype(md.mesh),'3D'),
+				list = {'Vx','Vy','Vz','Vel','Pressure'};
+			elseif strcmp(meshtype(md.mesh),'2Dhorizontal'),
+				list = {'Vx','Vy','Vel','Pressure'};
+			elseif strcmp(meshtype(md.mesh),'2Dvertical'),
+				list = {'Vx','Vy','Vel','Pressure'};
+			else
+				error('mesh type not supported yet');
+			end
+
 		end % }}}
 		function disp(obj) % {{{
@@ -172,8 +186,17 @@
 			WriteData(fid,'object',obj,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer');
 			WriteData(fid,'object',obj,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','requested_outputs','format','DoubleMat','mattype',3);
+
 			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
 			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
 			WriteData(fid,'data',obj.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum,'format','StringArray');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/stressbalance.py
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.py	(revision 16559)
+++ /issm/trunk/src/m/classes/stressbalance.py	(revision 16560)
@@ -6,4 +6,5 @@
 from checkfield import *
 from WriteData import *
+from MatlabFuncs import *
 
 class stressbalance(object):
@@ -34,5 +35,5 @@
 		self.referential              = float('NaN')
 		self.loadingforce             = float('NaN')
-		self.requested_outputs        = float('NaN')
+		self.requested_outputs        = []
 
 		#set defaults
@@ -102,5 +103,21 @@
 		self.rift_penalty_lock=10
 
+		#output default:
+		self.requested_outputs=['default']
+
 		return self
+	#}}}
+	def defaultoutputs(self,md): # {{{
+
+		if strcmp(md.mesh.meshtype(),'3D'):
+			list = ['Vx','Vy','Vz','Vel','Pressure']
+		elif strcmp(md.mesh.meshtype(),'2Dhorizontal'):
+			list = ['Vx','Vy','Vel','Pressure']
+		elif strcmp(md.mesh.meshtype(),'2Dvertical'):
+			list = ['Vx','Vy','Vel','Pressure']
+		else:
+			raise TypeError('mesh type not supported yet');
+		return list
+
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
@@ -112,5 +129,5 @@
 		md = checkfield(md,'stressbalance.spcvx','forcing',1)
 		md = checkfield(md,'stressbalance.spcvy','forcing',1)
-		if md.mesh.dimension==3:
+		if strcmp(md.mesh.meshtype(),'3D'):
 			md = checkfield(md,'stressbalance.spcvz','forcing',1)
 		md = checkfield(md,'stressbalance.restol','size',[1],'>',0)
@@ -123,6 +140,5 @@
 		md = checkfield(md,'stressbalance.referential','size',[md.mesh.numberofvertices,6])
 		md = checkfield(md,'stressbalance.loadingforce','size',[md.mesh.numberofvertices,3])
-		if not md.stressbalance.requested_outputs:
-			md = checkfield(md,'stressbalance.requested_outputs','size',[float('NaN'),1])
+		md = checkfield(md,'stressbalance.requested_outputs','stringrow',1);
 
 		#singular solution
@@ -145,6 +161,5 @@
 					md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
 		#CHECK THAT NO rotation specified for FS Grounded ice at base
-#		if md.mesh.dimension==3 & md.flowequation.isFS,
-		if md.mesh.dimension==3 and md.flowequation.isFS:
+		if strcmp(md.mesh.meshtype(),'3D') and md.flowequation.isFS:
 			pos=numpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbed))
 			if numpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):
@@ -173,7 +188,15 @@
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','requested_outputs','format','DoubleMat','mattype',3)
+
 		WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum())
 		WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum())
 		WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum())
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum(),'format','StringArray')
 	# }}}
Index: /issm/trunk/src/m/classes/taoinversion.m
===================================================================
--- /issm/trunk/src/m/classes/taoinversion.m	(revision 16559)
+++ /issm/trunk/src/m/classes/taoinversion.m	(revision 16560)
@@ -68,4 +68,8 @@
 			if ~obj.iscontrol, return; end
 
+			if ~IssmConfig('_HAVE_TAO_'),
+				md = checkmessage(md,['TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO']);
+			end
+
 			num_controls=numel(md.inversion.control_parameters);
 			num_costfunc=size(md.inversion.cost_functions,2);
@@ -75,5 +79,5 @@
 			md = checkfield(md,'inversion.control_parameters','cell',1,'values',...
 				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness'});
-			md = checkfield(md,'inversion.nsteps','numel',1,'>=',1);
+			md = checkfield(md,'inversion.nsteps','numel',1,'>=',0);
 			md = checkfield(md,'inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
 			md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 16559)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 16560)
@@ -13,5 +13,6 @@
 		penalty_factor    = 0;
 		isenthalpy        = 0;
-        	isdynamicbasalspc = 0;
+		isdynamicbasalspc = 0;
+		requested_outputs = {};
 	end
 	methods
@@ -23,4 +24,13 @@
 					error('constructor not supported');
 			end
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			if self.isenthalpy,
+				list = {'Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsMeltingRate'};
+			else
+				list = {'Temperature','BasalforcingsMeltingRate'};
+			end
+
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
@@ -40,7 +50,10 @@
 			%Should we use cold ice (default) or enthalpy formulation
 			obj.isenthalpy=0;
-            
-            		%will basal boundary conditions be set dynamically
-            		obj.isdynamicbasalspc=0;
+
+			%will basal boundary conditions be set dynamically
+			obj.isdynamicbasalspc=0;
+
+			%default output
+			obj.requested_outputs={'default'};
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -51,12 +64,17 @@
 			md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0 1 2]);
 			md = checkfield(md,'thermal.spctemperature','forcing',1);
-			if (ismember(EnthalpyAnalysisEnum(),analyses) & (md.thermal.isenthalpy | solution==EnthalpySolutionEnum()) & md.mesh.dimension==3),
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy & md.mesh.dimension==3),
 				pos=find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN);
 				replicate=repmat(md.geometry.surface-md.mesh.z,1,size(md.thermal.spctemperature,2));
 				md = checkfield(md,'thermal.spctemperature(find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN))','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate(pos),'message','spctemperature should be below the adjusted melting point');
 				md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0 1]);
-                		md = checkfield(md,'thermal.isdynamicbasalspc','numel',[1],'values',[0 1]);
-			end
-		end % }}}
+				md = checkfield(md,'thermal.isdynamicbasalspc','numel', [1],'values',[0 1]);
+				if(md.thermal.isenthalpy)
+					md = checkfield(md,'thermal.isdynamicbasalspc','numel', [1],'values',[1], 'message',['for enthalpy run thermal.isdynamicbasalspc should be 1']);
+				end
+	    end
+
+		 md = checkfield(md,'thermal.requested_outputs','stringrow',1);
+    end % }}} 
 		function disp(obj) % {{{
 			disp(sprintf('   Thermal solution parameters:'));
@@ -67,7 +85,9 @@
 			fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
 			fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)');
+			fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
 			fielddisplay(obj,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)');
-            		fielddisplay(obj,'isdynamicbasalspc',['enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)']);
-            
+			fielddisplay(obj,'isdynamicbasalspc',['enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)']);
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
+
 		end % }}}
 		function marshall(obj,md,fid) % {{{
@@ -79,5 +99,14 @@
 			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
 			WriteData(fid,'object',obj,'fieldname','isenthalpy','format','Boolean');
-            		WriteData(fid,'object',obj,'fieldname','isdynamicbasalspc','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isdynamicbasalspc','format','Boolean');
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray');
         	end % }}}
 	end
Index: /issm/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 16559)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 16560)
@@ -21,4 +21,6 @@
 		self.penalty_factor    = 0
 		self.isenthalpy        = 0
+		self.isdynamicbasalspc = 0;
+		self.requested_outputs = []
 
 		#set defaults
@@ -34,6 +36,16 @@
 		string="%s\n%s"%(string,fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
 		string="%s\n%s"%(string,fielddisplay(self,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdynamicbasalspc','enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 		return string
 		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		if self.isenthalpy:
+			return ['Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsMeltingRate']
+		else:
+			return ['Temperature','BasalforcingsMeltingRate']
+
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -53,5 +65,11 @@
 		self.isenthalpy=0
 
+		#will basal boundary conditions be set dynamically
+		self.isdynamicbasalspc=0;
+
+		#default output
+		self.requested_outputs=['default']
 		return self
+
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
@@ -63,9 +81,11 @@
 		md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0,1,2])
 		md = checkfield(md,'thermal.spctemperature','forcing',1)
-		if EnthalpyAnalysisEnum() in analyses and (md.thermal.isenthalpy or solution==EnthalpySolutionEnum()) and md.mesh.dimension==3:
+		if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension==3:
 			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
 			replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1)))
 			md = checkfield(md,'thermal.spctemperature[numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices,:])))]','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate[pos],'message',"spctemperature should be below the adjusted melting point")
 			md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0,1])
+			md = checkfield(md,'thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
+			md = checkfield(md,'thermal.requested_outputs','stringrow',1)
 
 		return md
@@ -79,3 +99,12 @@
 		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
 		WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdynamicbasalspc','format','Boolean');
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray')
 	# }}}
Index: /issm/trunk/src/m/classes/toolkits.m
===================================================================
--- /issm/trunk/src/m/classes/toolkits.m	(revision 16559)
+++ /issm/trunk/src/m/classes/toolkits.m	(revision 16560)
@@ -48,5 +48,11 @@
 				 end
 			 else
-				 obj.DefaultAnalysis           = issmsolver(); 
+				 if IssmConfig('_HAVE_MUMPS_'),
+					 obj.DefaultAnalysis           = issmmumpssolver(); 
+				 elseif IssmConfig('_HAVE_GSL_'),
+					 obj.DefaultAnalysis           = issmgslsolver(); 
+				 else 
+					 error('Need at least Mumps or Gsl to define an issm solver type');
+				 end
 			 end
 
Index: /issm/trunk/src/m/classes/toolkits.py
===================================================================
--- /issm/trunk/src/m/classes/toolkits.py	(revision 16559)
+++ /issm/trunk/src/m/classes/toolkits.py	(revision 16560)
@@ -25,5 +25,10 @@
 				self.DefaultAnalysis           = iluasmoptions()
 		else:
-			self.DefaultAnalysis           = issmsolver()
+			if IssmConfig('_HAVE_MUMPS_')[0]:
+				self.DefaultAnalysis           = issmmumpssolver()
+			elif IssmConfig('_HAVE_GSL_')[0]:
+				self.DefaultAnalysis           = issmgslsolver()
+			else:
+				raise IOError("ToolkitsFile error: need at least Mumps or Gsl to define issm solver type")
 
 		#The other properties are dynamic
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 16559)
+++ /issm/trunk/src/m/classes/transient.m	(revision 16560)
@@ -11,5 +11,6 @@
 		isgroundingline   = 0;
 		isgia             = 0;
-		requested_outputs = NaN;
+		isdamage             = 0;
+		requested_outputs = {};
 	end
 	methods
@@ -25,9 +26,17 @@
 
 			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-			obj.ismasstransport=1;
-			obj.isstressbalance=1;
-			obj.isthermal=1;
-			obj.isgroundingline=0;
-			obj.isgia=0;
+			obj.ismasstransport = 1;
+			obj.isstressbalance = 1;
+			obj.isthermal       = 1;
+			obj.isgroundingline = 0;
+			obj.isgia           = 0;
+			obj.isdamage        = 0;
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			list = {'SurfaceforcingsMassBalance'};
 
 		end % }}}
@@ -42,5 +51,6 @@
 			md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.isgia','numel',[1],'values',[0 1]);
-			md = checkfield(md,'transient.requested_outputs','size',[NaN 1]);
+			md = checkfield(md,'transient.isdamage','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.requested_outputs','stringrow',1);
 
 		end % }}}
@@ -48,9 +58,10 @@
 			disp(sprintf('   transient solution parameters:'));
 
-			fielddisplay(obj,'ismasstransport','indicates if a masstransport solution is used in the transient');
-			fielddisplay(obj,'isstressbalance','indicates if a stressbalance solution is used in the transient');
-			fielddisplay(obj,'isthermal','indicates if a thermal solution is used in the transient');
-			fielddisplay(obj,'isgroundingline','indicates if a groundingline migration is used in the transient');
-			fielddisplay(obj,'isgia','indicates if a postglacial rebound model is used in the transient');
+			fielddisplay(obj,'ismasstransport','indicates whether a masstransport solution is used in the transient');
+			fielddisplay(obj,'isstressbalance','indicates whether a stressbalance solution is used in the transient');
+			fielddisplay(obj,'isthermal','indicates whether a thermal solution is used in the transient');
+			fielddisplay(obj,'isgroundingline','indicates whether a groundingline migration is used in the transient');
+			fielddisplay(obj,'isgia','indicates whether a postglacial rebound model is used in the transient');
+			fielddisplay(obj,'isdamage','indicates whether damage evolution is used in the transient');
 			fielddisplay(obj,'requested_outputs','list of additional outputs requested');
 
@@ -62,5 +73,14 @@
 			WriteData(fid,'object',obj,'fieldname','isgroundingline','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','isgia','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','isdamage','format','Boolean');
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum,'format','StringArray');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 16559)
+++ /issm/trunk/src/m/classes/transient.py	(revision 16560)
@@ -18,5 +18,5 @@
 		self.isgroundingline   = False
 		self.isgia             = False
-		self.requested_outputs = float('NaN')
+		self.requested_outputs = []
 
 		#set defaults
@@ -34,13 +34,20 @@
 		return string
 		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		return ['SurfaceforcingsMassBalance']
+
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
 		#full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-		self.ismasstransport=True
-		self.isstressbalance=True
-		self.isthermal=True
-		self.isgroundingline=False
-		self.isgia=False
+		self.ismasstransport = True
+		self.isstressbalance = True
+		self.isthermal       = True
+		self.isgroundingline = False
+		self.isgia           = False
 
+		#default output
+		self.requested_outputs=['default']
 		return self
 	#}}}
@@ -56,6 +63,5 @@
 		md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0,1])
 		md = checkfield(md,'transient.isgia','numel',[1],'values',[0,1])
-		md = checkfield(md,'transient.requested_outputs','size',[float('NaN')])
-
+		md = checkfield(md,'transient.requested_outputs','stringrow',1)
 
 		return md
@@ -67,5 +73,11 @@
 		WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','isgia','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum(),'format','StringArray')
 	# }}}
-
Index: /issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.m	(revision 16559)
+++ /issm/trunk/src/m/consistency/checkfield.m	(revision 16560)
@@ -164,4 +164,18 @@
 end
 
+%Check row of strings
+if getfieldvalue(options,'stringrow',0),
+	if(size(field,1)~=1 & size(field,1)~=0),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have only one row']));
+	end
+	for i=1:size(field,2),
+		if ~ischar(field{i}),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' values should a cell of chars']));
+		end
+	end
+end
+
 %check file
 if getfieldvalue(options,'file',0),
Index: /issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.py	(revision 16559)
+++ /issm/trunk/src/m/consistency/checkfield.py	(revision 16560)
@@ -138,4 +138,10 @@
 			md = md.checkmessage("file provided in '%s': '%s' does not exist" % (fieldname,field))
 
+	#Check row of strings
+	if options.exist('stringrow'):
+		if not isinstance(field,list):
+			md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should be a list" %fieldname))
+
 	#Check forcings (size and times)
 	if options.getfieldvalue('forcing',0):
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 16559)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 16560)
@@ -10,5 +10,5 @@
 %Get solution and associated analyses
 solution=md.private.solution;
-[analyses,numanalyses]=AnalysisConfiguration(solution);
+[analyses]=AnalysisConfiguration(solution);
 
 %Go through a model field, check that it is a class, and call checkconsistency
@@ -37,67 +37,53 @@
 end
 
-function [analyses,numanalyses]=AnalysisConfiguration(solutiontype), % {{{
+function [analyses]=AnalysisConfiguration(solutiontype), % {{{
 %ANALYSISCONFIGURATION - return type of analyses, number of analyses 
 %
 %   Usage:
-%      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+%      [analyses]=AnalysisConfiguration(solutiontype);
 
 switch solutiontype,
 
 	case StressbalanceSolutionEnum(),
-		numanalyses=5;
-		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum()];
 
 	case SteadystateSolutionEnum(),
-		numanalyses=7; 
-		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
 
 	case ThermalSolutionEnum(),
-		numanalyses=2; 
-		analyses=[ThermalAnalysisEnum();MeltingAnalysisEnum()];
-
-	case EnthalpySolutionEnum(),
-		numanalyses=1; 
-		analyses=[EnthalpyAnalysisEnum()];
+		analyses=[EnthalpyAnalysisEnum;ThermalAnalysisEnum();MeltingAnalysisEnum()];
 
 	case MasstransportSolutionEnum(),
-		numanalyses=1; 
 		analyses=[MasstransportAnalysisEnum()];
 
 	case BalancethicknessSolutionEnum(),
-		numanalyses=1; 
 		analyses=[BalancethicknessAnalysisEnum()];
 
 	case BalancethicknessSoftSolutionEnum(),
-		numanalyses=1; 
 		analyses=[BalancethicknessAnalysisEnum()];
 
 	case BalancevelocitySolutionEnum(),
-		numanalyses=1; 
 		analyses=[BalancevelocityAnalysisEnum()];
 
 	case SurfaceSlopeSolutionEnum(),
-		numanalyses=1; 
-		analyses=[SurfaceSlopeAnalysisEnum()];
+		analyses=[L2ProjectionBaseAnalysisEnum()];
 
 	case BedSlopeSolutionEnum(),
-		numanalyses=1; 
-		analyses=[BedSlopeAnalysisEnum()];
+		analyses=[L2ProjectionBaseAnalysisEnum()];
 
 	case GiaSolutionEnum(),
-		numanalyses=1; 
 		analyses=[GiaAnalysisEnum()];
 
 	case TransientSolutionEnum(),
-		numanalyses=9; 
-		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();MasstransportAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();MasstransportAnalysisEnum()];
 
 	case FlaimSolutionEnum(),
-		numanalyses=1; 
 		analyses=[FlaimAnalysisEnum()];
 
 	case HydrologySolutionEnum(),
-		numanalyses=3; 
-		analyses=[BedSlopeAnalysisEnum();SurfaceSlopeAnalysisEnum();HydrologyShreveAnalysisEnum();HydrologyDCInefficientAnalysisEnum();HydrologyDCEfficientAnalysisEnum()];
+		analyses=[L2ProjectionBaseAnalysisEnum();HydrologyShreveAnalysisEnum();HydrologyDCInefficientAnalysisEnum();HydrologyDCEfficientAnalysisEnum()];
+	
+	case DamageEvolutionSolutionEnum(),
+		analyses=[DamageEvolutionAnalysisEnum()];
 
 	otherwise
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 16559)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 16560)
@@ -7,63 +7,47 @@
 
 		Usage:
-			[analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+			[analyses]=AnalysisConfiguration(solutiontype);
 	"""
 
 	if   solutiontype == StressbalanceSolutionEnum():
-		numanalyses=5
-		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum()]
 
 	elif solutiontype == SteadystateSolutionEnum():
-		numanalyses=7 
-		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
 
 	elif solutiontype == ThermalSolutionEnum():
-		numanalyses=2 
-		analyses=[ThermalAnalysisEnum(),MeltingAnalysisEnum()]
-
-	elif solutiontype == EnthalpySolutionEnum():
-		numanalyses=1 
-		analyses=[EnthalpyAnalysisEnum()]
+		analyses=[EnthalpyAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
 
 	elif solutiontype == MasstransportSolutionEnum():
-		numanalyses=1 
 		analyses=[MasstransportAnalysisEnum()]
 
 	elif solutiontype == BalancethicknessSolutionEnum():
-		numanalyses=1 
 		analyses=[BalancethicknessAnalysisEnum()]
 
 	elif solutiontype == SurfaceSlopeSolutionEnum():
-		numanalyses=1 
-		analyses=[SurfaceSlopeAnalysisEnum()]
+		analyses=[L2ProjectionBaseAnalysisEnum()]
 
 	elif solutiontype == BalancevelocitySolutionEnum():
-		numanalyses=1 
 		analyses=[BalancevelocityAnalysisEnum()]
 
 	elif solutiontype == BedSlopeSolutionEnum():
-		numanalyses=1 
-		analyses=[BedSlopeAnalysisEnum()]
+		analyses=[L2ProjectionBaseAnalysisEnum()]
 
 	elif solutiontype == GiaSolutionEnum():
-		numanalyses=1
 		analyses=[GiaAnalysisEnum()]
 
 	elif solutiontype == TransientSolutionEnum():
-		numanalyses=9 
-		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]
 
 	elif solutiontype == FlaimSolutionEnum():
-		numanalyses=1 
 		analyses=[FlaimAnalysisEnum()]
 
 	elif solutiontype == HydrologySolutionEnum():
-		numanalyses=3 
-		analyses=[BedSlopeAnalysisEnum(),SurfaceSlopeAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]
+		analyses=[L2ProjectionBaseAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]
 
 	else:
 		raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])
 
-	return analyses,numanalyses
+	return analyses
 #}}}
 
@@ -81,5 +65,5 @@
 	#Get solution and associated analyses
 	solution=md.private.solution
-	analyses,numanalyses=AnalysisConfiguration(solution)
+	analyses=AnalysisConfiguration(solution)
 
 	#Go through a model fields, check that it is a class, and call checkconsistency
Index: /issm/trunk/src/m/contrib/dassflow/exportgmsh.m
===================================================================
--- /issm/trunk/src/m/contrib/dassflow/exportgmsh.m	(revision 16560)
+++ /issm/trunk/src/m/contrib/dassflow/exportgmsh.m	(revision 16560)
@@ -0,0 +1,52 @@
+function exportgmsh(mesh,groundedice_levelset,filename),
+%EXPORTGMSH - export mesh to gmsh format
+%
+%   http://www.geuz.org/gmsh/doc/texinfo/#MSH-ASCII-file-format
+%
+%   Usage:
+%      exportgmsh(mesh,groundedice_levelset,filename)
+%
+%   Example:
+%      exportgmsh(md.mesh,md.mask.groundedice_levelset,'temp.msh')
+
+fid=fopen(filename,'w');
+
+%Header
+fprintf(fid,'$MeshFormat\n');
+fprintf(fid,'2.2 0 8\n');
+fprintf(fid,'$EndMeshFormat\n');
+
+%Vertices
+nbv = mesh.numberofvertices;
+fprintf(fid,'$Nodes\n');
+fprintf(fid,'%i\n',nbv);
+fprintf(fid,'%i %8g %8g %8g\n',[[1:nbv]' mesh.x mesh.y zeros(nbv,1)]');
+fprintf(fid,'$EndNodes\n');
+
+%Boundary Elements first
+nbe     = mesh.numberofelements;
+nbs     = size(mesh.segments,1);
+segment = 1;
+tria    = 2;
+
+%Create flags
+grounded = sum(groundedice_levelset(mesh.segments(:,1:2))>0,2);
+A = zeros(nbs,2);
+pos = find(mesh.segmentmarkers==4);
+A(pos,:)=repmat([1,4],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==1 &  grounded);
+A(pos,:)=repmat([2,1],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==1 & ~grounded);
+A(pos,:)=repmat([3,5],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==2);
+A(pos,:)=repmat([4,2],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==3);
+A(pos,:)=repmat([5,3],[numel(pos) 1]);
+
+fprintf(fid,'$Elements\n');
+fprintf(fid,'%i\n',nbe+nbs);
+fprintf(fid,'%i %i %i %i %i %i %i\n',[[1    :nbs    ]' segment*ones(nbs,1) 2*ones(nbs,1) A mesh.segments(:,1:2)]');
+fprintf(fid,'%i %i %i %i %i %i %i %i\n',[[nbs+1:nbs+nbe]' tria*ones(nbe,1) 2*ones(nbe,1) 7*ones(nbe,1) 6*ones(nbe,1) mesh.elements]');
+fprintf(fid,'$EndElements\n');
+
+fclose(fid);
Index: /issm/trunk/src/m/contrib/dassflow/importgmsh.m
===================================================================
--- /issm/trunk/src/m/contrib/dassflow/importgmsh.m	(revision 16560)
+++ /issm/trunk/src/m/contrib/dassflow/importgmsh.m	(revision 16560)
@@ -0,0 +1,90 @@
+function md = importgmsh(filename)
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+
+%open file
+fid=fopen(filename,'r');
+
+%Get Mesh format
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$MeshFormat'), 
+	error(['Expecting $MeshFormat (' A ')']);
+end
+A=fscanf(fid,'%f %i %i',[1 3]);
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$EndMeshFormat'), 
+	error(['Expecting $EndMeshFormat (' A ')']);
+end
+
+%Nodes
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$Nodes'), 
+	error(['Expecting $Nodes (' A ')']);
+end
+nbv=fscanf(fid,'%i',1);
+disp(['Number of nodes: ' num2str(nbv) ]);
+A=fscanf(fid,'%i %f %f %f',[4 nbv]);
+x = A(2,:)';
+y = A(3,:)';
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$EndNodes'), 
+	error(['Expecting $EndNodes (' A ')']);
+end
+
+%Elements
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$Elements'), 
+	error(['Expecting $Elements (' A ')']);
+end
+nbt=fscanf(fid,'%i',1);
+disp(['Number of elements: ' num2str(nbt) ]);
+counter = 0;
+index   = zeros(0,3);
+segments       = zeros(0,2);
+segmentmarkers = zeros(0,1);
+while(counter<nbt);
+	id = fscanf(fid,'%i',1);
+	ty = fscanf(fid,'%i',1);
+	if(ty>2) error('Type not supported'); end
+	nbf = fscanf(fid,'%i',1);
+	flags = fscanf(fid,'%i',nbf);
+
+	if ty==1,
+		A=fscanf(fid,'%i %i',2);
+		segments(end+1,:)=A;
+		if(flags(1)==5 & flags(2)==3), segmentmarkers(end+1)=3; 
+		elseif(flags(1)==1 & flags(2)==4), segmentmarkers(end+1)=4;
+		elseif(flags(1)==2 & flags(2)==1), segmentmarkers(end+1)=1;
+		elseif(flags(1)==4 & flags(2)==2), segmentmarkers(end+1)=2;
+		else error(['flags ' num2str(flags') ' not supported']);
+		end
+	else
+		A=fscanf(fid,'%i %i %i',3);
+		index(end+1,:)=A;
+	end
+	counter = counter + 1;
+end
+
+%recreate segments
+nbs = size(segments,1);
+segments = [segments zeros(nbs,1)];
+for i=1:nbs,
+	E = find(sum(ismember(index,segments(i,:)),2)>1);
+	segments(i,3)=E;
+end
+
+%close file
+fclose(fid);
+
+%Create model
+md=meshconvert(model,index,x,y);
+md.mesh=mesh2dvertical(md.mesh);
+md.mesh.segmentmarkers=segmentmarkers;
+md.mesh.segments=segments;
+md.mesh.vertexonbed=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed(find(vertexflags(md.mesh,1)))=1;
+md.mesh.vertexonsurface=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface(find(vertexflags(md.mesh,3)))=1;
Index: /issm/trunk/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 16559)
+++ /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 16560)
@@ -17,6 +17,6 @@
 end
 
-%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
-WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
+%First, write MaximumNumberOfDefinitionsEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',true,'format','Boolean');
 
 %Write all data
@@ -26,4 +26,9 @@
 WriteData(fid,'enum',3,'data',x_interp,'format','DoubleMat');
 WriteData(fid,'enum',4,'data',y_interp,'format','DoubleMat');
+
+%Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',true,'format','Boolean');
+
+%Now, write number of options
 options.marshall(fid,5);
 st=fclose(fid);
Index: /issm/trunk/src/m/contrib/paraview/exportVTK.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 16559)
+++ /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 16560)
@@ -1,8 +1,9 @@
-function exportVTK(filename,model,Solution)
+function exportVTK(filename,model,varargin)
 % vtk export
-% function exportVTK(filename,model,Solution)
-% creates a directory with the vtk files for you simulation
+% function exportVTK(filename,model)
+% creates a directory with the vtk files for displays in paraview
 % (only work for triangle and wedges based on their number of nodes)
-% and additional cell data
+%
+%Give only the results for nw but could be extended to geometry, mask... 
 %
 % input: filename   destination 
@@ -11,6 +12,8 @@
 %        model      this is md 
 %------------------------------------------------------------------
-%        Solution   Put on the enum of the solution you want 
-%	                  to plot         
+% By default only the results are exported, you can add whichever
+% field you need as a string:
+% add 'geometry' to export md.geometry
+%
 % Basile de Fleurian:
 
@@ -19,11 +22,9 @@
 mkdir(filename);
 
+%get the element related variables
 points=[model.mesh.x model.mesh.y model.mesh.z];
 [num_of_points,dim]=size(points);
 [num_of_elt]=size(model.mesh.elements,1);
 [point_per_elt]=size(model.mesh.elements,2);
-sol_enum=EnumToString(Solution);
-
-sol_struct=model.results.(sol_enum);
 
 %Select the type of element function of the number of nodes per elements
@@ -36,19 +37,27 @@
 end
 
+%this is the result structure
+res_struct=model.results;
+%Getting all the solutions of the model
+solnames=fields(res_struct);
+num_of_sols=length(solnames);
+%building solution structure 
+for i=1:num_of_sols
+	sol_struct{i}=res_struct.(solnames{i});
+end
+
 %looking for multiple time steps
-num_of_timesteps=size(sol_struct,2);
+num_of_timesteps=size(sol_struct{1},2);
 
-%getting the number of fields in the solution
-fieldnames=fields(sol_struct(1));
-num_of_fields=length(fieldnames);
-
-if num_of_timesteps==1; %just one timestep only write one file
-
-	FID = fopen(strcat(path,filesep,name,filesep,name,'.vtk'),'w+');
+for step=1:num_of_timesteps;
+	%by default, we take the timestep from the first solution sturcture
+	timestep=sol_struct{1}(step).step;
+	
+	FID = fopen(strcat(path,filesep,name,filesep,name,'.vtk',int2str(timestep),'.vtk'),'w+');
 	fprintf(FID,'# vtk DataFile Version 2.0 \n');
 	fprintf(FID,'Data for run %s \n',model.miscellaneous.name);
 	fprintf(FID,'ASCII \n');
 	fprintf(FID,'DATASET UNSTRUCTURED_GRID \n');
-
+	
 	fprintf(FID,'POINTS %d float\n',num_of_points);
 	if(dim==3);
@@ -59,71 +68,58 @@
 	P=[points zeros(num_of_points,3-dim)];
 	fprintf(FID,s,P');
-
+	
 	fprintf(FID,'CELLS %d %d\n',num_of_elt,num_of_elt*(point_per_elt+1));
 	s='%d';
-	for k=1:point_per_elt
-    s=horzcat(s,{' %d'});
+	for j=1:point_per_elt
+		s=horzcat(s,{' %d'});
   end
 	s=cell2mat(horzcat(s,{'\n'}));
 	fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
-
+	
 	fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
 	s='%d\n';
 	fprintf(FID,s,celltype*ones(num_of_elt,1));
+	fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
 
-	%check which field is a real result and print	
-	fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
-	for j=1:num_of_fields
-
-		if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
-			fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
-			fprintf(FID,'LOOKUP_TABLE default\n');
-			s='%e\n';
-			fprintf(FID,s,sol_struct.(fieldnames{j}));
-	  end
-  end
-		fclose(FID);
-else
-	for i=1:num_of_timesteps;
-		timestep=sol_struct(i).step;
-		FID = fopen(strcat(path,filesep,name,filesep,name,'.vtk',int2str(timestep),'.vtk'),'w+');
-		fprintf(FID,'# vtk DataFile Version 2.0 \n');
-		fprintf(FID,'Data for run %s \n',model.miscellaneous.name);
-		fprintf(FID,'ASCII \n');
-		fprintf(FID,'DATASET UNSTRUCTURED_GRID \n');
-
-		fprintf(FID,'POINTS %d float\n',num_of_points);
-		if(dim==3);
-			s='%f %f %f \n';
-		elseif(dim==2);
-			s='%f %f \n';
-   end
-		P=[points zeros(num_of_points,3-dim)];
-		fprintf(FID,s,P');
-
-		fprintf(FID,'CELLS %d %d\n',num_of_elt,num_of_elt*(point_per_elt+1));
-		s='%d';
-		for k=1:point_per_elt
-			s=horzcat(s,{' %d'});
-  	end
-		s=cell2mat(horzcat(s,{'\n'}));
-		fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
-
-		fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
-		s='%d\n';
-		fprintf(FID,s,celltype*ones(num_of_elt,1));
-
+	%loop over the different solution structures
+	for j=1:num_of_sols
+		
+		%getting the number of fields in the solution
+		fieldnames=fields(sol_struct{j}(step));
+		num_of_fields=length(fieldnames);
+		
 		%check which field is a real result and print
-		fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
-		for j=1:num_of_fields
-
-			if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
-				fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
+			for k=1:num_of_fields
+			if ((length(sol_struct{j}(step).(fieldnames{k})))== ...
+					num_of_points);
+				%paraview does not like NaN, replacing
+				pos=find(isnan(sol_struct{j}(step).(fieldnames{k})));
+				sol_struct{j}(step).(fieldnames{k})(pos)=-9999;
+				fprintf(FID,'SCALARS %s float 1 \n',fieldnames{k});
 				fprintf(FID,'LOOKUP_TABLE default\n');
 				s='%e\n';
-				fprintf(FID,s,sol_struct(i).(fieldnames{j}));
+				fprintf(FID,s,sol_struct{j}(step).(fieldnames{k}));
+    	end		
+	  end 
+	end
+	
+	%loop on arguments, if something other than result is asked, do
+	%it now
+	for j= 1:nargin-2
+		res_struct=model.(varargin{j});
+		solnames=fields(res_struct);
+		num_of_sols=length(solnames);
+		for k=1:num_of_sols
+			if ((length(res_struct.(solnames{k})))==num_of_points);
+				%paraview does not like NaN, replacing
+				pos=find(isnan(res_struct.(solnames{k})));
+				res_struct.(solnames{k})(pos)=-9999;
+				fprintf(FID,'SCALARS %s float 1 \n',solnames{k});
+				fprintf(FID,'LOOKUP_TABLE default\n');
+				s='%e\n';
+				fprintf(FID,s,res_struct.(solnames{k}));
 	    end		
-    end 
-		fclose(FID);
-  end
+		end 
+	end
+	fclose(FID);
 end
Index: /issm/trunk/src/m/dev/devpath.py
===================================================================
--- /issm/trunk/src/m/dev/devpath.py	(revision 16559)
+++ /issm/trunk/src/m/dev/devpath.py	(revision 16560)
@@ -24,3 +24,9 @@
 from plotmodel import plotmodel
 
+c = get_ipython().config
+c.InteractiveShellApp.exec_lines = []
+c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
+c.InteractiveShellApp.exec_lines.append('%autoreload 2')
+c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in startup.py to improve performance." ')
+
 print("\n  ISSM development path correctly loaded\n\n")
Index: /issm/trunk/src/m/dev/issmversion.m
===================================================================
--- /issm/trunk/src/m/dev/issmversion.m	(revision 16560)
+++ /issm/trunk/src/m/dev/issmversion.m	(revision 16560)
@@ -0,0 +1,20 @@
+function issmversion(),
+%ISSMVERSION - display ISSM version
+%
+%   Usage:
+%      issmversion()
+
+
+if exist('IssmConfig')~=3,
+	error('ISSM not correctly installed. IssmConfig not found');
+end
+
+disp([' ']);
+disp([IssmConfig('PACKAGE_NAME') ' Version ' IssmConfig('PACKAGE_VERSION')]);
+disp(['(website: ' IssmConfig('PACKAGE_URL') ' contact:' IssmConfig('PACKAGE_BUGREPORT') ')']);
+disp([' ']);
+disp(['Build date: ' IssmConfig('PACKAGE_BUILD_DATE')]);
+disp(['Copyright (c) 2009-2013 California Institute of Technology']);
+disp([' ']);
+disp(['    to get started type: issmdoc']);
+disp([' ']);
Index: /issm/trunk/src/m/dev/issmversion.py
===================================================================
--- /issm/trunk/src/m/dev/issmversion.py	(revision 16560)
+++ /issm/trunk/src/m/dev/issmversion.py	(revision 16560)
@@ -0,0 +1,20 @@
+from IssmConfig import IssmConfig
+
+def issmversion():
+	"""
+	ISSMVERSION - display ISSM version
+
+		Usage:
+			issmversion()
+	"""
+
+
+print ' '
+print IssmConfig('PACKAGE_NAME')[0]+' Version '+IssmConfig('PACKAGE_VERSION')[0]
+print '(website: '+IssmConfig('PACKAGE_URL')[0]+' contact:'+IssmConfig('PACKAGE_BUGREPORT')[0]+')'
+print ' '
+print 'Build date: '+IssmConfig('PACKAGE_BUILD_DATE')[0]
+print 'Copyright (c) 2009-2013 California Institute of Technology'
+print ' '
+print '    to get started type: issmdoc'
+print ' '
Index: sm/trunk/src/m/enum/AdjointSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointSolutionEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=AdjointSolutionEnum()
-%ADJOINTSOLUTIONENUM - Enum of AdjointSolution
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=AdjointSolutionEnum()
-
-macro=StringToEnum('AdjointSolution');
Index: /issm/trunk/src/m/enum/AutodiffCbufsizeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffCbufsizeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffCbufsizeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffCbufsizeEnum()
+%AUTODIFFCBUFSIZEENUM - Enum of AutodiffCbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffCbufsizeEnum()
+
+macro=StringToEnum('AutodiffCbufsize');
Index: /issm/trunk/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffGcTriggerMaxSizeEnum()
+%AUTODIFFGCTRIGGERMAXSIZEENUM - Enum of AutodiffGcTriggerMaxSize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffGcTriggerMaxSizeEnum()
+
+macro=StringToEnum('AutodiffGcTriggerMaxSize');
Index: /issm/trunk/src/m/enum/AutodiffGcTriggerRatioEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffGcTriggerRatioEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffGcTriggerRatioEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffGcTriggerRatioEnum()
+%AUTODIFFGCTRIGGERRATIOENUM - Enum of AutodiffGcTriggerRatio
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffGcTriggerRatioEnum()
+
+macro=StringToEnum('AutodiffGcTriggerRatio');
Index: /issm/trunk/src/m/enum/AutodiffLbufsizeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffLbufsizeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffLbufsizeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffLbufsizeEnum()
+%AUTODIFFLBUFSIZEENUM - Enum of AutodiffLbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffLbufsizeEnum()
+
+macro=StringToEnum('AutodiffLbufsize');
Index: /issm/trunk/src/m/enum/AutodiffObufsizeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffObufsizeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffObufsizeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffObufsizeEnum()
+%AUTODIFFOBUFSIZEENUM - Enum of AutodiffObufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffObufsizeEnum()
+
+macro=StringToEnum('AutodiffObufsize');
Index: /issm/trunk/src/m/enum/AutodiffTbufsizeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffTbufsizeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/AutodiffTbufsizeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=AutodiffTbufsizeEnum()
+%AUTODIFFTBUFSIZEENUM - Enum of AutodiffTbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffTbufsizeEnum()
+
+macro=StringToEnum('AutodiffTbufsize');
Index: sm/trunk/src/m/enum/BasisIntegralEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasisIntegralEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BasisIntegralEnum()
-%BASISINTEGRALENUM - Enum of BasisIntegral
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BasisIntegralEnum()
-
-macro=StringToEnum('BasisIntegral');
Index: sm/trunk/src/m/enum/BedSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BedSlopeAnalysisEnum()
-%BEDSLOPEANALYSISENUM - Enum of BedSlopeAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BedSlopeAnalysisEnum()
-
-macro=StringToEnum('BedSlopeAnalysis');
Index: sm/trunk/src/m/enum/BedSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeXAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BedSlopeXAnalysisEnum()
-%BEDSLOPEXANALYSISENUM - Enum of BedSlopeXAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BedSlopeXAnalysisEnum()
-
-macro=StringToEnum('BedSlopeXAnalysis');
Index: sm/trunk/src/m/enum/BedSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeYAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BedSlopeYAnalysisEnum()
-%BEDSLOPEYANALYSISENUM - Enum of BedSlopeYAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BedSlopeYAnalysisEnum()
-
-macro=StringToEnum('BedSlopeYAnalysis');
Index: sm/trunk/src/m/enum/BoolElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoolElementResultEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BoolElementResultEnum()
-%BOOLELEMENTRESULTENUM - Enum of BoolElementResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BoolElementResultEnum()
-
-macro=StringToEnum('BoolElementResult');
Index: sm/trunk/src/m/enum/ConstantEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=ConstantEnum()
-%CONSTANTENUM - Enum of Constant
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=ConstantEnum()
-
-macro=StringToEnum('Constant');
Index: /issm/trunk/src/m/enum/DamageC1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageC1Enum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageC1Enum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageC1Enum()
+%DAMAGEC1ENUM - Enum of DamageC1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC1Enum()
+
+macro=StringToEnum('DamageC1');
Index: /issm/trunk/src/m/enum/DamageC2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageC2Enum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageC2Enum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageC2Enum()
+%DAMAGEC2ENUM - Enum of DamageC2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC2Enum()
+
+macro=StringToEnum('DamageC2');
Index: /issm/trunk/src/m/enum/DamageC3Enum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageC3Enum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageC3Enum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageC3Enum()
+%DAMAGEC3ENUM - Enum of DamageC3
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC3Enum()
+
+macro=StringToEnum('DamageC3');
Index: /issm/trunk/src/m/enum/DamageC4Enum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageC4Enum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageC4Enum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageC4Enum()
+%DAMAGEC4ENUM - Enum of DamageC4
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC4Enum()
+
+macro=StringToEnum('DamageC4');
Index: /issm/trunk/src/m/enum/DamageDEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageDEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageDEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageDEnum()
+%DAMAGEDENUM - Enum of DamageD
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageDEnum()
+
+macro=StringToEnum('DamageD');
Index: /issm/trunk/src/m/enum/DamageDbarEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageDbarEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageDbarEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageDbarEnum()
+%DAMAGEDBARENUM - Enum of DamageDbar
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageDbarEnum()
+
+macro=StringToEnum('DamageDbar');
Index: /issm/trunk/src/m/enum/DamageEvolutionAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageEvolutionAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageEvolutionAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionAnalysisEnum()
+%DAMAGEEVOLUTIONANALYSISENUM - Enum of DamageEvolutionAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionAnalysisEnum()
+
+macro=StringToEnum('DamageEvolutionAnalysis');
Index: /issm/trunk/src/m/enum/DamageEvolutionSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageEvolutionSolutionEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageEvolutionSolutionEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionSolutionEnum()
+%DAMAGEEVOLUTIONSOLUTIONENUM - Enum of DamageEvolutionSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionSolutionEnum()
+
+macro=StringToEnum('DamageEvolutionSolution');
Index: /issm/trunk/src/m/enum/DamageHealingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageHealingEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageHealingEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageHealingEnum()
+%DAMAGEHEALINGENUM - Enum of DamageHealing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageHealingEnum()
+
+macro=StringToEnum('DamageHealing');
Index: /issm/trunk/src/m/enum/DamageLawEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageLawEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageLawEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageLawEnum()
+%DAMAGELAWENUM - Enum of DamageLaw
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageLawEnum()
+
+macro=StringToEnum('DamageLaw');
Index: /issm/trunk/src/m/enum/DamageMaxDamageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageMaxDamageEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageMaxDamageEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageMaxDamageEnum()
+%DAMAGEMAXDAMAGEENUM - Enum of DamageMaxDamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageMaxDamageEnum()
+
+macro=StringToEnum('DamageMaxDamage');
Index: /issm/trunk/src/m/enum/DamageMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageMaxiterEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageMaxiterEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageMaxiterEnum()
+%DAMAGEMAXITERENUM - Enum of DamageMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageMaxiterEnum()
+
+macro=StringToEnum('DamageMaxiter');
Index: /issm/trunk/src/m/enum/DamagePenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamagePenaltyFactorEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamagePenaltyFactorEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyFactorEnum()
+%DAMAGEPENALTYFACTORENUM - Enum of DamagePenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyFactorEnum()
+
+macro=StringToEnum('DamagePenaltyFactor');
Index: /issm/trunk/src/m/enum/DamagePenaltyLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamagePenaltyLockEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamagePenaltyLockEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyLockEnum()
+%DAMAGEPENALTYLOCKENUM - Enum of DamagePenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyLockEnum()
+
+macro=StringToEnum('DamagePenaltyLock');
Index: /issm/trunk/src/m/enum/DamagePenaltyThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamagePenaltyThresholdEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamagePenaltyThresholdEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyThresholdEnum()
+%DAMAGEPENALTYTHRESHOLDENUM - Enum of DamagePenaltyThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyThresholdEnum()
+
+macro=StringToEnum('DamagePenaltyThreshold');
Index: /issm/trunk/src/m/enum/DamageSpcdamageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageSpcdamageEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageSpcdamageEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageSpcdamageEnum()
+%DAMAGESPCDAMAGEENUM - Enum of DamageSpcdamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageSpcdamageEnum()
+
+macro=StringToEnum('DamageSpcdamage');
Index: /issm/trunk/src/m/enum/DamageStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageStabilizationEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageStabilizationEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageStabilizationEnum()
+%DAMAGESTABILIZATIONENUM - Enum of DamageStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageStabilizationEnum()
+
+macro=StringToEnum('DamageStabilization');
Index: /issm/trunk/src/m/enum/DamageStressThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageStressThresholdEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/DamageStressThresholdEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=DamageStressThresholdEnum()
+%DAMAGESTRESSTHRESHOLDENUM - Enum of DamageStressThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageStressThresholdEnum()
+
+macro=StringToEnum('DamageStressThreshold');
Index: sm/trunk/src/m/enum/DofIndexingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DofIndexingEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DofIndexingEnum()
-%DOFINDEXINGENUM - Enum of DofIndexing
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=DofIndexingEnum()
-
-macro=StringToEnum('DofIndexing');
Index: sm/trunk/src/m/enum/DoubleElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleElementResultEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DoubleElementResultEnum()
-%DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=DoubleElementResultEnum()
-
-macro=StringToEnum('DoubleElementResult');
Index: sm/trunk/src/m/enum/ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ElementResultEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=ElementResultEnum()
-%ELEMENTRESULTENUM - Enum of ElementResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=ElementResultEnum()
-
-macro=StringToEnum('ElementResult');
Index: sm/trunk/src/m/enum/EnthalpySolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EnthalpySolutionEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=EnthalpySolutionEnum()
-%ENTHALPYSOLUTIONENUM - Enum of EnthalpySolution
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=EnthalpySolutionEnum()
-
-macro=StringToEnum('EnthalpySolution');
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 16559)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 16560)
@@ -29,4 +29,10 @@
 def AutodiffMassFluxSegmentsPresentEnum(): return StringToEnum("AutodiffMassFluxSegmentsPresent")[0]
 def AutodiffKeepEnum(): return StringToEnum("AutodiffKeep")[0]
+def AutodiffObufsizeEnum(): return StringToEnum("AutodiffObufsize")[0]
+def AutodiffLbufsizeEnum(): return StringToEnum("AutodiffLbufsize")[0]
+def AutodiffCbufsizeEnum(): return StringToEnum("AutodiffCbufsize")[0]
+def AutodiffTbufsizeEnum(): return StringToEnum("AutodiffTbufsize")[0]
+def AutodiffGcTriggerRatioEnum(): return StringToEnum("AutodiffGcTriggerRatio")[0]
+def AutodiffGcTriggerMaxSizeEnum(): return StringToEnum("AutodiffGcTriggerMaxSize")[0]
 def BalancethicknessSpcthicknessEnum(): return StringToEnum("BalancethicknessSpcthickness")[0]
 def BalancethicknessStabilizationEnum(): return StringToEnum("BalancethicknessStabilization")[0]
@@ -42,11 +48,10 @@
 def DependentObjectEnum(): return StringToEnum("DependentObject")[0]
 def StressbalanceAbstolEnum(): return StringToEnum("StressbalanceAbstol")[0]
-def StressbalanceIcefrontEnum(): return StringToEnum("StressbalanceIcefront")[0]
 def StressbalanceIsnewtonEnum(): return StringToEnum("StressbalanceIsnewton")[0]
 def StressbalanceMaxiterEnum(): return StringToEnum("StressbalanceMaxiter")[0]
-def StressbalanceNumRequestedOutputsEnum(): return StringToEnum("StressbalanceNumRequestedOutputs")[0]
 def StressbalancePenaltyFactorEnum(): return StringToEnum("StressbalancePenaltyFactor")[0]
 def StressbalanceReferentialEnum(): return StringToEnum("StressbalanceReferential")[0]
 def StressbalanceReltolEnum(): return StringToEnum("StressbalanceReltol")[0]
+def StressbalanceNumRequestedOutputsEnum(): return StringToEnum("StressbalanceNumRequestedOutputs")[0]
 def StressbalanceRequestedOutputsEnum(): return StringToEnum("StressbalanceRequestedOutputs")[0]
 def StressbalanceRestolEnum(): return StringToEnum("StressbalanceRestol")[0]
@@ -118,5 +123,4 @@
 def HydrologyEfficientEnum(): return StringToEnum("HydrologyEfficient")[0]
 def HydrologySedimentKmaxEnum(): return StringToEnum("HydrologySedimentKmax")[0]
-def BasisIntegralEnum(): return StringToEnum("BasisIntegral")[0]
 def WaterTransferEnum(): return StringToEnum("WaterTransfer")[0]
 def IndependentObjectEnum(): return StringToEnum("IndependentObject")[0]
@@ -125,5 +129,4 @@
 def InversionCostFunctionsCoefficientsEnum(): return StringToEnum("InversionCostFunctionsCoefficients")[0]
 def InversionCostFunctionsEnum(): return StringToEnum("InversionCostFunctions")[0]
-def InversionGradientOnlyEnum(): return StringToEnum("InversionGradientOnly")[0]
 def InversionGradientScalingEnum(): return StringToEnum("InversionGradientScaling")[0]
 def InversionIscontrolEnum(): return StringToEnum("InversionIscontrol")[0]
@@ -138,9 +141,9 @@
 def InversionStepThresholdEnum(): return StringToEnum("InversionStepThreshold")[0]
 def InversionThicknessObsEnum(): return StringToEnum("InversionThicknessObs")[0]
-def InversionVelObsEnum(): return StringToEnum("InversionVelObs")[0]
 def InversionVxObsEnum(): return StringToEnum("InversionVxObs")[0]
 def InversionVyObsEnum(): return StringToEnum("InversionVyObs")[0]
 def InversionVzObsEnum(): return StringToEnum("InversionVzObs")[0]
 def MaskIceLevelsetEnum(): return StringToEnum("MaskIceLevelset")[0]
+def QmuMaskIceLevelsetEnum(): return StringToEnum("QmuMaskIceLevelset")[0]
 def MaterialsBetaEnum(): return StringToEnum("MaterialsBeta")[0]
 def MaterialsHeatcapacityEnum(): return StringToEnum("MaterialsHeatcapacity")[0]
@@ -152,6 +155,21 @@
 def MaterialsRheologyLawEnum(): return StringToEnum("MaterialsRheologyLaw")[0]
 def MaterialsRheologyNEnum(): return StringToEnum("MaterialsRheologyN")[0]
-def MaterialsRheologyZEnum(): return StringToEnum("MaterialsRheologyZ")[0]
-def MaterialsRheologyZbarEnum(): return StringToEnum("MaterialsRheologyZbar")[0]
+def DamageDEnum(): return StringToEnum("DamageD")[0]
+def QmuDamageDEnum(): return StringToEnum("QmuDamageD")[0]
+def DamageDbarEnum(): return StringToEnum("DamageDbar")[0]
+def DamageLawEnum(): return StringToEnum("DamageLaw")[0]
+def DamageC1Enum(): return StringToEnum("DamageC1")[0]
+def DamageC2Enum(): return StringToEnum("DamageC2")[0]
+def DamageC3Enum(): return StringToEnum("DamageC3")[0]
+def DamageC4Enum(): return StringToEnum("DamageC4")[0]
+def DamageHealingEnum(): return StringToEnum("DamageHealing")[0]
+def DamageStressThresholdEnum(): return StringToEnum("DamageStressThreshold")[0]
+def DamageStabilizationEnum(): return StringToEnum("DamageStabilization")[0]
+def DamagePenaltyThresholdEnum(): return StringToEnum("DamagePenaltyThreshold")[0]
+def DamagePenaltyLockEnum(): return StringToEnum("DamagePenaltyLock")[0]
+def DamagePenaltyFactorEnum(): return StringToEnum("DamagePenaltyFactor")[0]
+def DamageMaxiterEnum(): return StringToEnum("DamageMaxiter")[0]
+def DamageSpcdamageEnum(): return StringToEnum("DamageSpcdamage")[0]
+def DamageMaxDamageEnum(): return StringToEnum("DamageMaxDamage")[0]
 def MaterialsRhoIceEnum(): return StringToEnum("MaterialsRhoIce")[0]
 def MaterialsRhoWaterEnum(): return StringToEnum("MaterialsRhoWater")[0]
@@ -165,5 +183,4 @@
 def MaterialsMantleDensityEnum(): return StringToEnum("MaterialsMantleDensity")[0]
 def MeshAverageVertexConnectivityEnum(): return StringToEnum("MeshAverageVertexConnectivity")[0]
-def MeshDimensionEnum(): return StringToEnum("MeshDimension")[0]
 def MeshElementonbedEnum(): return StringToEnum("MeshElementonbed")[0]
 def MeshElementonsurfaceEnum(): return StringToEnum("MeshElementonsurface")[0]
@@ -182,4 +199,8 @@
 def MeshYEnum(): return StringToEnum("MeshY")[0]
 def MeshZEnum(): return StringToEnum("MeshZ")[0]
+def MeshTypeEnum(): return StringToEnum("MeshType")[0]
+def Mesh2DhorizontalEnum(): return StringToEnum("Mesh2Dhorizontal")[0]
+def Mesh2DverticalEnum(): return StringToEnum("Mesh2Dvertical")[0]
+def Mesh3DEnum(): return StringToEnum("Mesh3D")[0]
 def MiscellaneousNameEnum(): return StringToEnum("MiscellaneousName")[0]
 def MasstransportHydrostaticAdjustmentEnum(): return StringToEnum("MasstransportHydrostaticAdjustment")[0]
@@ -207,5 +228,4 @@
 def SettingsLowmemEnum(): return StringToEnum("SettingsLowmem")[0]
 def SettingsOutputFrequencyEnum(): return StringToEnum("SettingsOutputFrequency")[0]
-def SettingsResultsAsPatchesEnum(): return StringToEnum("SettingsResultsAsPatches")[0]
 def SettingsWaitonlockEnum(): return StringToEnum("SettingsWaitonlock")[0]
 def SurfaceforcingsDelta18oEnum(): return StringToEnum("SurfaceforcingsDelta18o")[0]
@@ -244,4 +264,6 @@
 def ThermalSpctemperatureEnum(): return StringToEnum("ThermalSpctemperature")[0]
 def ThermalStabilizationEnum(): return StringToEnum("ThermalStabilization")[0]
+def ThermalNumRequestedOutputsEnum(): return StringToEnum("ThermalNumRequestedOutputs")[0]
+def ThermalRequestedOutputsEnum(): return StringToEnum("ThermalRequestedOutputs")[0]
 def GiaMantleViscosityEnum(): return StringToEnum("GiaMantleViscosity")[0]
 def GiaLithosphereThicknessEnum(): return StringToEnum("GiaLithosphereThickness")[0]
@@ -257,4 +279,5 @@
 def TransientIsthermalEnum(): return StringToEnum("TransientIsthermal")[0]
 def TransientIsgiaEnum(): return StringToEnum("TransientIsgia")[0]
+def TransientIsdamageEnum(): return StringToEnum("TransientIsdamage")[0]
 def TransientNumRequestedOutputsEnum(): return StringToEnum("TransientNumRequestedOutputs")[0]
 def TransientRequestedOutputsEnum(): return StringToEnum("TransientRequestedOutputs")[0]
@@ -264,7 +287,5 @@
 def AdjointBalancethicknessAnalysisEnum(): return StringToEnum("AdjointBalancethicknessAnalysis")[0]
 def AdjointHorizAnalysisEnum(): return StringToEnum("AdjointHorizAnalysis")[0]
-def AdjointSolutionEnum(): return StringToEnum("AdjointSolution")[0]
 def AnalysisCounterEnum(): return StringToEnum("AnalysisCounter")[0]
-def NoneAnalysisEnum(): return StringToEnum("NoneAnalysis")[0]
 def DefaultAnalysisEnum(): return StringToEnum("DefaultAnalysis")[0]
 def BalancethicknessAnalysisEnum(): return StringToEnum("BalancethicknessAnalysis")[0]
@@ -274,8 +295,8 @@
 def BalancevelocityAnalysisEnum(): return StringToEnum("BalancevelocityAnalysis")[0]
 def BalancevelocitySolutionEnum(): return StringToEnum("BalancevelocitySolution")[0]
-def BedSlopeAnalysisEnum(): return StringToEnum("BedSlopeAnalysis")[0]
+def L2ProjectionBaseAnalysisEnum(): return StringToEnum("L2ProjectionBaseAnalysis")[0]
 def BedSlopeSolutionEnum(): return StringToEnum("BedSlopeSolution")[0]
-def BedSlopeXAnalysisEnum(): return StringToEnum("BedSlopeXAnalysis")[0]
-def BedSlopeYAnalysisEnum(): return StringToEnum("BedSlopeYAnalysis")[0]
+def DamageEvolutionSolutionEnum(): return StringToEnum("DamageEvolutionSolution")[0]
+def DamageEvolutionAnalysisEnum(): return StringToEnum("DamageEvolutionAnalysis")[0]
 def StressbalanceAnalysisEnum(): return StringToEnum("StressbalanceAnalysis")[0]
 def StressbalanceSIAAnalysisEnum(): return StringToEnum("StressbalanceSIAAnalysis")[0]
@@ -283,5 +304,4 @@
 def StressbalanceVerticalAnalysisEnum(): return StringToEnum("StressbalanceVerticalAnalysis")[0]
 def EnthalpyAnalysisEnum(): return StringToEnum("EnthalpyAnalysis")[0]
-def EnthalpySolutionEnum(): return StringToEnum("EnthalpySolution")[0]
 def FlaimAnalysisEnum(): return StringToEnum("FlaimAnalysis")[0]
 def FlaimSolutionEnum(): return StringToEnum("FlaimSolution")[0]
@@ -295,9 +315,9 @@
 def FreeSurfaceBaseAnalysisEnum(): return StringToEnum("FreeSurfaceBaseAnalysis")[0]
 def FreeSurfaceTopAnalysisEnum(): return StringToEnum("FreeSurfaceTopAnalysis")[0]
+def ExtrudeFromBaseAnalysisEnum(): return StringToEnum("ExtrudeFromBaseAnalysis")[0]
+def ExtrudeFromTopAnalysisEnum(): return StringToEnum("ExtrudeFromTopAnalysis")[0]
 def SteadystateSolutionEnum(): return StringToEnum("SteadystateSolution")[0]
-def SurfaceSlopeAnalysisEnum(): return StringToEnum("SurfaceSlopeAnalysis")[0]
+def L2ProjectionTopAnalysisEnum(): return StringToEnum("L2ProjectionTopAnalysis")[0]
 def SurfaceSlopeSolutionEnum(): return StringToEnum("SurfaceSlopeSolution")[0]
-def SurfaceSlopeXAnalysisEnum(): return StringToEnum("SurfaceSlopeXAnalysis")[0]
-def SurfaceSlopeYAnalysisEnum(): return StringToEnum("SurfaceSlopeYAnalysis")[0]
 def SmoothedSurfaceSlopeXAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeXAnalysis")[0]
 def SmoothedSurfaceSlopeYAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeYAnalysis")[0]
@@ -307,4 +327,6 @@
 def GiaSolutionEnum(): return StringToEnum("GiaSolution")[0]
 def GiaAnalysisEnum(): return StringToEnum("GiaAnalysis")[0]
+def MeshdeformationSolutionEnum(): return StringToEnum("MeshdeformationSolution")[0]
+def MeshdeformationAnalysisEnum(): return StringToEnum("MeshdeformationAnalysis")[0]
 def ApproximationEnum(): return StringToEnum("Approximation")[0]
 def NoneApproximationEnum(): return StringToEnum("NoneApproximation")[0]
@@ -334,5 +356,4 @@
 def ControlInputEnum(): return StringToEnum("ControlInput")[0]
 def DatasetInputEnum(): return StringToEnum("DatasetInput")[0]
-def DofIndexingEnum(): return StringToEnum("DofIndexing")[0]
 def DoubleInputEnum(): return StringToEnum("DoubleInput")[0]
 def DataSetParamEnum(): return StringToEnum("DataSetParam")[0]
@@ -342,19 +363,14 @@
 def DoubleVecParamEnum(): return StringToEnum("DoubleVecParam")[0]
 def ElementEnum(): return StringToEnum("Element")[0]
-def ElementResultEnum(): return StringToEnum("ElementResult")[0]
 def ExternalResultEnum(): return StringToEnum("ExternalResult")[0]
 def FileParamEnum(): return StringToEnum("FileParam")[0]
-def HookEnum(): return StringToEnum("Hook")[0]
-def IcefrontEnum(): return StringToEnum("Icefront")[0]
 def InputEnum(): return StringToEnum("Input")[0]
 def IntInputEnum(): return StringToEnum("IntInput")[0]
+def InputToExtrudeEnum(): return StringToEnum("InputToExtrude")[0]
+def InputToL2ProjectEnum(): return StringToEnum("InputToL2Project")[0]
 def IntParamEnum(): return StringToEnum("IntParam")[0]
 def IntVecParamEnum(): return StringToEnum("IntVecParam")[0]
 def TransientParamEnum(): return StringToEnum("TransientParam")[0]
-def IceFrontTypeEnum(): return StringToEnum("IceFrontType")[0]
-def SSA2dIceFrontEnum(): return StringToEnum("SSA2dIceFront")[0]
-def SSA3dIceFrontEnum(): return StringToEnum("SSA3dIceFront")[0]
 def MaticeEnum(): return StringToEnum("Matice")[0]
-def MatdamageiceEnum(): return StringToEnum("Matdamageice")[0]
 def MatparEnum(): return StringToEnum("Matpar")[0]
 def NodeEnum(): return StringToEnum("Node")[0]
@@ -362,6 +378,4 @@
 def NumericalfluxTypeEnum(): return StringToEnum("NumericalfluxType")[0]
 def ParamEnum(): return StringToEnum("Param")[0]
-def L1L2IceFrontEnum(): return StringToEnum("L1L2IceFront")[0]
-def HOIceFrontEnum(): return StringToEnum("HOIceFront")[0]
 def PengridEnum(): return StringToEnum("Pengrid")[0]
 def PenpairEnum(): return StringToEnum("Penpair")[0]
@@ -379,7 +393,8 @@
 def SpcStaticEnum(): return StringToEnum("SpcStatic")[0]
 def SpcTransientEnum(): return StringToEnum("SpcTransient")[0]
-def FSIceFrontEnum(): return StringToEnum("FSIceFront")[0]
 def StringArrayParamEnum(): return StringToEnum("StringArrayParam")[0]
 def StringParamEnum(): return StringToEnum("StringParam")[0]
+def SegEnum(): return StringToEnum("Seg")[0]
+def SegInputEnum(): return StringToEnum("SegInput")[0]
 def TriaEnum(): return StringToEnum("Tria")[0]
 def TriaInputEnum(): return StringToEnum("TriaInput")[0]
@@ -402,5 +417,4 @@
 def BedSlopeYEnum(): return StringToEnum("BedSlopeY")[0]
 def BoundaryEnum(): return StringToEnum("Boundary")[0]
-def ConstantEnum(): return StringToEnum("Constant")[0]
 def ConvergedEnum(): return StringToEnum("Converged")[0]
 def FillEnum(): return StringToEnum("Fill")[0]
@@ -410,8 +424,6 @@
 def InternalEnum(): return StringToEnum("Internal")[0]
 def MassFluxEnum(): return StringToEnum("MassFlux")[0]
-def MaxPenetrationEnum(): return StringToEnum("MaxPenetration")[0]
 def MeltingOffsetEnum(): return StringToEnum("MeltingOffset")[0]
 def MisfitEnum(): return StringToEnum("Misfit")[0]
-def NumberNodeToElementConnectivityEnum(): return StringToEnum("NumberNodeToElementConnectivity")[0]
 def PressureEnum(): return StringToEnum("Pressure")[0]
 def PressurePicardEnum(): return StringToEnum("PressurePicard")[0]
@@ -439,5 +451,4 @@
 def SurfaceSlopeYEnum(): return StringToEnum("SurfaceSlopeY")[0]
 def TemperatureEnum(): return StringToEnum("Temperature")[0]
-def TemperatureOldEnum(): return StringToEnum("TemperatureOld")[0]
 def TemperaturePicardEnum(): return StringToEnum("TemperaturePicard")[0]
 def ThicknessAbsMisfitEnum(): return StringToEnum("ThicknessAbsMisfit")[0]
@@ -463,5 +474,4 @@
 def ThicknessAlongGradientEnum(): return StringToEnum("ThicknessAlongGradient")[0]
 def ThicknessAcrossGradientEnum(): return StringToEnum("ThicknessAcrossGradient")[0]
-def StepResponsesEnum(): return StringToEnum("StepResponses")[0]
 def IntMatParamEnum(): return StringToEnum("IntMatParam")[0]
 def RheologyBbarAbsGradientEnum(): return StringToEnum("RheologyBbarAbsGradient")[0]
@@ -499,20 +509,18 @@
 def TaylorHoodEnum(): return StringToEnum("TaylorHood")[0]
 def SaveResultsEnum(): return StringToEnum("SaveResults")[0]
-def BoolElementResultEnum(): return StringToEnum("BoolElementResult")[0]
 def BoolExternalResultEnum(): return StringToEnum("BoolExternalResult")[0]
-def DoubleElementResultEnum(): return StringToEnum("DoubleElementResult")[0]
 def DoubleExternalResultEnum(): return StringToEnum("DoubleExternalResult")[0]
 def DoubleMatExternalResultEnum(): return StringToEnum("DoubleMatExternalResult")[0]
 def IntExternalResultEnum(): return StringToEnum("IntExternalResult")[0]
 def JEnum(): return StringToEnum("J")[0]
-def PatchEnum(): return StringToEnum("Patch")[0]
-def PatchNodesEnum(): return StringToEnum("PatchNodes")[0]
-def PatchVerticesEnum(): return StringToEnum("PatchVertices")[0]
-def PentaP1ElementResultEnum(): return StringToEnum("PentaP1ElementResult")[0]
 def StringExternalResultEnum(): return StringToEnum("StringExternalResult")[0]
 def StepEnum(): return StringToEnum("Step")[0]
 def TimeEnum(): return StringToEnum("Time")[0]
-def TriaP1ElementResultEnum(): return StringToEnum("TriaP1ElementResult")[0]
 def WaterColumnOldEnum(): return StringToEnum("WaterColumnOld")[0]
+def OutputdefinitionEnum(): return StringToEnum("Outputdefinition")[0]
+def OutputdefinitionListEnum(): return StringToEnum("OutputdefinitionList")[0]
+def MassfluxatgateEnum(): return StringToEnum("Massfluxatgate")[0]
+def MassfluxatgateNameEnum(): return StringToEnum("MassfluxatgateName")[0]
+def MassfluxatgateSegmentsEnum(): return StringToEnum("MassfluxatgateSegments")[0]
 def MinVelEnum(): return StringToEnum("MinVel")[0]
 def MaxVelEnum(): return StringToEnum("MaxVel")[0]
@@ -527,4 +535,5 @@
 def MaxAbsVzEnum(): return StringToEnum("MaxAbsVz")[0]
 def IceVolumeEnum(): return StringToEnum("IceVolume")[0]
+def IceVolumeAboveFloatationEnum(): return StringToEnum("IceVolumeAboveFloatation")[0]
 def TotalSmbEnum(): return StringToEnum("TotalSmb")[0]
 def AbsoluteEnum(): return StringToEnum("Absolute")[0]
@@ -536,4 +545,5 @@
 def SubelementMigration2Enum(): return StringToEnum("SubelementMigration2")[0]
 def MaskGroundediceLevelsetEnum(): return StringToEnum("MaskGroundediceLevelset")[0]
+def QmuMaskGroundediceLevelsetEnum(): return StringToEnum("QmuMaskGroundediceLevelset")[0]
 def FSSolverEnum(): return StringToEnum("FSSolver")[0]
 def AdjointEnum(): return StringToEnum("Adjoint")[0]
@@ -572,13 +582,13 @@
 def DenseEnum(): return StringToEnum("Dense")[0]
 def MpiDenseEnum(): return StringToEnum("MpiDense")[0]
+def MpiSparseEnum(): return StringToEnum("MpiSparse")[0]
 def SeqEnum(): return StringToEnum("Seq")[0]
 def MpiEnum(): return StringToEnum("Mpi")[0]
+def MumpsEnum(): return StringToEnum("Mumps")[0]
+def GslEnum(): return StringToEnum("Gsl")[0]
 def OptionEnum(): return StringToEnum("Option")[0]
 def GenericOptionEnum(): return StringToEnum("GenericOption")[0]
 def OptionCellEnum(): return StringToEnum("OptionCell")[0]
-def OptionCharEnum(): return StringToEnum("OptionChar")[0]
 def OptionStructEnum(): return StringToEnum("OptionStruct")[0]
-def OptionDoubleEnum(): return StringToEnum("OptionDouble")[0]
-def OptionLogicalEnum(): return StringToEnum("OptionLogical")[0]
 def PatersonEnum(): return StringToEnum("Paterson")[0]
 def ArrheniusEnum(): return StringToEnum("Arrhenius")[0]
Index: /issm/trunk/src/m/enum/ExtrudeFromBaseAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ExtrudeFromBaseAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/ExtrudeFromBaseAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=ExtrudeFromBaseAnalysisEnum()
+%EXTRUDEFROMBASEANALYSISENUM - Enum of ExtrudeFromBaseAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrudeFromBaseAnalysisEnum()
+
+macro=StringToEnum('ExtrudeFromBaseAnalysis');
Index: /issm/trunk/src/m/enum/ExtrudeFromTopAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ExtrudeFromTopAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/ExtrudeFromTopAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=ExtrudeFromTopAnalysisEnum()
+%EXTRUDEFROMTOPANALYSISENUM - Enum of ExtrudeFromTopAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrudeFromTopAnalysisEnum()
+
+macro=StringToEnum('ExtrudeFromTopAnalysis');
Index: sm/trunk/src/m/enum/FSIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSIceFrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FSIceFrontEnum()
-%FSICEFRONTENUM - Enum of FSIceFront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=FSIceFrontEnum()
-
-macro=StringToEnum('FSIceFront');
Index: /issm/trunk/src/m/enum/GslEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GslEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/GslEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=GslEnum()
+%GSLENUM - Enum of Gsl
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GslEnum()
+
+macro=StringToEnum('Gsl');
Index: sm/trunk/src/m/enum/HOIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HOIceFrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HOIceFrontEnum()
-%HOICEFRONTENUM - Enum of HOIceFront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=HOIceFrontEnum()
-
-macro=StringToEnum('HOIceFront');
Index: sm/trunk/src/m/enum/HookEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HookEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HookEnum()
-%HOOKENUM - Enum of Hook
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=HookEnum()
-
-macro=StringToEnum('Hook');
Index: sm/trunk/src/m/enum/IceFrontTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceFrontTypeEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=IceFrontTypeEnum()
-%ICEFRONTTYPEENUM - Enum of IceFrontType
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=IceFrontTypeEnum()
-
-macro=StringToEnum('IceFrontType');
Index: /issm/trunk/src/m/enum/IceVolumeAboveFloatationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceVolumeAboveFloatationEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/IceVolumeAboveFloatationEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=IceVolumeAboveFloatationEnum()
+%ICEVOLUMEABOVEFLOATATIONENUM - Enum of IceVolumeAboveFloatation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceVolumeAboveFloatationEnum()
+
+macro=StringToEnum('IceVolumeAboveFloatation');
Index: sm/trunk/src/m/enum/IcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IcefrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=IcefrontEnum()
-%ICEFRONTENUM - Enum of Icefront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=IcefrontEnum()
-
-macro=StringToEnum('Icefront');
Index: /issm/trunk/src/m/enum/InputToExtrudeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InputToExtrudeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/InputToExtrudeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=InputToExtrudeEnum()
+%INPUTTOEXTRUDEENUM - Enum of InputToExtrude
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToExtrudeEnum()
+
+macro=StringToEnum('InputToExtrude');
Index: /issm/trunk/src/m/enum/InputToL2ProjectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InputToL2ProjectEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/InputToL2ProjectEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=InputToL2ProjectEnum()
+%INPUTTOL2PROJECTENUM - Enum of InputToL2Project
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToL2ProjectEnum()
+
+macro=StringToEnum('InputToL2Project');
Index: sm/trunk/src/m/enum/InversionGradientOnlyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionGradientOnlyEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=InversionGradientOnlyEnum()
-%INVERSIONGRADIENTONLYENUM - Enum of InversionGradientOnly
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=InversionGradientOnlyEnum()
-
-macro=StringToEnum('InversionGradientOnly');
Index: sm/trunk/src/m/enum/InversionVelObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionVelObsEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=InversionVelObsEnum()
-%INVERSIONVELOBSENUM - Enum of InversionVelObs
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=InversionVelObsEnum()
-
-macro=StringToEnum('InversionVelObs');
Index: sm/trunk/src/m/enum/L1L2IceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L1L2IceFrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=L1L2IceFrontEnum()
-%L1L2ICEFRONTENUM - Enum of L1L2IceFront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=L1L2IceFrontEnum()
-
-macro=StringToEnum('L1L2IceFront');
Index: /issm/trunk/src/m/enum/L2ProjectionBaseAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L2ProjectionBaseAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/L2ProjectionBaseAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=L2ProjectionBaseAnalysisEnum()
+%L2PROJECTIONBASEANALYSISENUM - Enum of L2ProjectionBaseAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=L2ProjectionBaseAnalysisEnum()
+
+macro=StringToEnum('L2ProjectionBaseAnalysis');
Index: /issm/trunk/src/m/enum/L2ProjectionTopAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L2ProjectionTopAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/L2ProjectionTopAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=L2ProjectionTopAnalysisEnum()
+%L2PROJECTIONTOPANALYSISENUM - Enum of L2ProjectionTopAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=L2ProjectionTopAnalysisEnum()
+
+macro=StringToEnum('L2ProjectionTopAnalysis');
Index: /issm/trunk/src/m/enum/MassfluxatgateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassfluxatgateEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MassfluxatgateEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateEnum()
+%MASSFLUXATGATEENUM - Enum of Massfluxatgate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateEnum()
+
+macro=StringToEnum('Massfluxatgate');
Index: /issm/trunk/src/m/enum/MassfluxatgateNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassfluxatgateNameEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MassfluxatgateNameEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateNameEnum()
+%MASSFLUXATGATENAMEENUM - Enum of MassfluxatgateName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateNameEnum()
+
+macro=StringToEnum('MassfluxatgateName');
Index: /issm/trunk/src/m/enum/MassfluxatgateSegmentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassfluxatgateSegmentsEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MassfluxatgateSegmentsEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateSegmentsEnum()
+%MASSFLUXATGATESEGMENTSENUM - Enum of MassfluxatgateSegments
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateSegmentsEnum()
+
+macro=StringToEnum('MassfluxatgateSegments');
Index: sm/trunk/src/m/enum/MatdamageiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MatdamageiceEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MatdamageiceEnum()
-%MATDAMAGEICEENUM - Enum of Matdamageice
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MatdamageiceEnum()
-
-macro=StringToEnum('Matdamageice');
Index: sm/trunk/src/m/enum/MaterialsRheologyZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaterialsRheologyZEnum()
-%MATERIALSRHEOLOGYZENUM - Enum of MaterialsRheologyZ
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MaterialsRheologyZEnum()
-
-macro=StringToEnum('MaterialsRheologyZ');
Index: sm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaterialsRheologyZbarEnum()
-%MATERIALSRHEOLOGYZBARENUM - Enum of MaterialsRheologyZbar
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MaterialsRheologyZbarEnum()
-
-macro=StringToEnum('MaterialsRheologyZbar');
Index: sm/trunk/src/m/enum/MaxPenetrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxPenetrationEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaxPenetrationEnum()
-%MAXPENETRATIONENUM - Enum of MaxPenetration
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MaxPenetrationEnum()
-
-macro=StringToEnum('MaxPenetration');
Index: /issm/trunk/src/m/enum/Mesh2DhorizontalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/Mesh2DhorizontalEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/Mesh2DhorizontalEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=Mesh2DhorizontalEnum()
+%MESH2DHORIZONTALENUM - Enum of Mesh2Dhorizontal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Mesh2DhorizontalEnum()
+
+macro=StringToEnum('Mesh2Dhorizontal');
Index: /issm/trunk/src/m/enum/Mesh2DverticalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/Mesh2DverticalEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/Mesh2DverticalEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=Mesh2DverticalEnum()
+%MESH2DVERTICALENUM - Enum of Mesh2Dvertical
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Mesh2DverticalEnum()
+
+macro=StringToEnum('Mesh2Dvertical');
Index: /issm/trunk/src/m/enum/Mesh3DEnum.m
===================================================================
--- /issm/trunk/src/m/enum/Mesh3DEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/Mesh3DEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=Mesh3DEnum()
+%MESH3DENUM - Enum of Mesh3D
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Mesh3DEnum()
+
+macro=StringToEnum('Mesh3D');
Index: sm/trunk/src/m/enum/MeshDimensionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshDimensionEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MeshDimensionEnum()
-%MESHDIMENSIONENUM - Enum of MeshDimension
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MeshDimensionEnum()
-
-macro=StringToEnum('MeshDimension');
Index: /issm/trunk/src/m/enum/MeshTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshTypeEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MeshTypeEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MeshTypeEnum()
+%MESHTYPEENUM - Enum of MeshType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshTypeEnum()
+
+macro=StringToEnum('MeshType');
Index: /issm/trunk/src/m/enum/MeshdeformationAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshdeformationAnalysisEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MeshdeformationAnalysisEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MeshdeformationAnalysisEnum()
+%MESHDEFORMATIONANALYSISENUM - Enum of MeshdeformationAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshdeformationAnalysisEnum()
+
+macro=StringToEnum('MeshdeformationAnalysis');
Index: /issm/trunk/src/m/enum/MeshdeformationSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshdeformationSolutionEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MeshdeformationSolutionEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MeshdeformationSolutionEnum()
+%MESHDEFORMATIONSOLUTIONENUM - Enum of MeshdeformationSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshdeformationSolutionEnum()
+
+macro=StringToEnum('MeshdeformationSolution');
Index: /issm/trunk/src/m/enum/MpiSparseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MpiSparseEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MpiSparseEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MpiSparseEnum()
+%MPISPARSEENUM - Enum of MpiSparse
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MpiSparseEnum()
+
+macro=StringToEnum('MpiSparse');
Index: /issm/trunk/src/m/enum/MumpsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MumpsEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/MumpsEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=MumpsEnum()
+%MUMPSENUM - Enum of Mumps
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MumpsEnum()
+
+macro=StringToEnum('Mumps');
Index: sm/trunk/src/m/enum/NoneAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NoneAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=NoneAnalysisEnum()
-%NONEANALYSISENUM - Enum of NoneAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=NoneAnalysisEnum()
-
-macro=StringToEnum('NoneAnalysis');
Index: sm/trunk/src/m/enum/NumberNodeToElementConnectivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NumberNodeToElementConnectivityEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=NumberNodeToElementConnectivityEnum()
-%NUMBERNODETOELEMENTCONNECTIVITYENUM - Enum of NumberNodeToElementConnectivity
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=NumberNodeToElementConnectivityEnum()
-
-macro=StringToEnum('NumberNodeToElementConnectivity');
Index: sm/trunk/src/m/enum/OptionCharEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionCharEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=OptionCharEnum()
-%OPTIONCHARENUM - Enum of OptionChar
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=OptionCharEnum()
-
-macro=StringToEnum('OptionChar');
Index: sm/trunk/src/m/enum/OptionDoubleEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionDoubleEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=OptionDoubleEnum()
-%OPTIONDOUBLEENUM - Enum of OptionDouble
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=OptionDoubleEnum()
-
-macro=StringToEnum('OptionDouble');
Index: sm/trunk/src/m/enum/OptionLogicalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionLogicalEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=OptionLogicalEnum()
-%OPTIONLOGICALENUM - Enum of OptionLogical
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=OptionLogicalEnum()
-
-macro=StringToEnum('OptionLogical');
Index: /issm/trunk/src/m/enum/OutputdefinitionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OutputdefinitionEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/OutputdefinitionEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=OutputdefinitionEnum()
+%OUTPUTDEFINITIONENUM - Enum of Outputdefinition
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputdefinitionEnum()
+
+macro=StringToEnum('Outputdefinition');
Index: /issm/trunk/src/m/enum/OutputdefinitionListEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OutputdefinitionListEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/OutputdefinitionListEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=OutputdefinitionListEnum()
+%OUTPUTDEFINITIONLISTENUM - Enum of OutputdefinitionList
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputdefinitionListEnum()
+
+macro=StringToEnum('OutputdefinitionList');
Index: sm/trunk/src/m/enum/PatchEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PatchEnum()
-%PATCHENUM - Enum of Patch
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=PatchEnum()
-
-macro=StringToEnum('Patch');
Index: sm/trunk/src/m/enum/PatchNodesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchNodesEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PatchNodesEnum()
-%PATCHNODESENUM - Enum of PatchNodes
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=PatchNodesEnum()
-
-macro=StringToEnum('PatchNodes');
Index: sm/trunk/src/m/enum/PatchVerticesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchVerticesEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PatchVerticesEnum()
-%PATCHVERTICESENUM - Enum of PatchVertices
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=PatchVerticesEnum()
-
-macro=StringToEnum('PatchVertices');
Index: sm/trunk/src/m/enum/PentaP1ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaP1ElementResultEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PentaP1ElementResultEnum()
-%PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=PentaP1ElementResultEnum()
-
-macro=StringToEnum('PentaP1ElementResult');
Index: /issm/trunk/src/m/enum/QmuDamageDEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuDamageDEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/QmuDamageDEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=QmuDamageDEnum()
+%QMUDAMAGEDENUM - Enum of QmuDamageD
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuDamageDEnum()
+
+macro=StringToEnum('QmuDamageD');
Index: /issm/trunk/src/m/enum/QmuMaskGroundediceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaskGroundediceLevelsetEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/QmuMaskGroundediceLevelsetEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=QmuMaskGroundediceLevelsetEnum()
+%QMUMASKGROUNDEDICELEVELSETENUM - Enum of QmuMaskGroundediceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMaskGroundediceLevelsetEnum()
+
+macro=StringToEnum('QmuMaskGroundediceLevelset');
Index: /issm/trunk/src/m/enum/QmuMaskIceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaskIceLevelsetEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/QmuMaskIceLevelsetEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=QmuMaskIceLevelsetEnum()
+%QMUMASKICELEVELSETENUM - Enum of QmuMaskIceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMaskIceLevelsetEnum()
+
+macro=StringToEnum('QmuMaskIceLevelset');
Index: sm/trunk/src/m/enum/SSA2dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSA2dIceFrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SSA2dIceFrontEnum()
-%SSA2DICEFRONTENUM - Enum of SSA2dIceFront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SSA2dIceFrontEnum()
-
-macro=StringToEnum('SSA2dIceFront');
Index: sm/trunk/src/m/enum/SSA3dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSA3dIceFrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SSA3dIceFrontEnum()
-%SSA3DICEFRONTENUM - Enum of SSA3dIceFront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SSA3dIceFrontEnum()
-
-macro=StringToEnum('SSA3dIceFront');
Index: /issm/trunk/src/m/enum/SegEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SegEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/SegEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=SegEnum()
+%SEGENUM - Enum of Seg
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegEnum()
+
+macro=StringToEnum('Seg');
Index: /issm/trunk/src/m/enum/SegInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SegInputEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/SegInputEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=SegInputEnum()
+%SEGINPUTENUM - Enum of SegInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegInputEnum()
+
+macro=StringToEnum('SegInput');
Index: sm/trunk/src/m/enum/SettingsResultsAsPatchesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsResultsAsPatchesEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SettingsResultsAsPatchesEnum()
-%SETTINGSRESULTSASPATCHESENUM - Enum of SettingsResultsAsPatches
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SettingsResultsAsPatchesEnum()
-
-macro=StringToEnum('SettingsResultsAsPatches');
Index: sm/trunk/src/m/enum/StepResponsesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StepResponsesEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=StepResponsesEnum()
-%STEPRESPONSESENUM - Enum of StepResponses
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=StepResponsesEnum()
-
-macro=StringToEnum('StepResponses');
Index: sm/trunk/src/m/enum/StressbalanceIcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceIcefrontEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=StressbalanceIcefrontEnum()
-%STRESSBALANCEICEFRONTENUM - Enum of StressbalanceIcefront
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=StressbalanceIcefrontEnum()
-
-macro=StringToEnum('StressbalanceIcefront');
Index: sm/trunk/src/m/enum/SurfaceSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SurfaceSlopeAnalysisEnum()
-%SURFACESLOPEANALYSISENUM - Enum of SurfaceSlopeAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SurfaceSlopeAnalysisEnum()
-
-macro=StringToEnum('SurfaceSlopeAnalysis');
Index: sm/trunk/src/m/enum/SurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeXAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SurfaceSlopeXAnalysisEnum()
-%SURFACESLOPEXANALYSISENUM - Enum of SurfaceSlopeXAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SurfaceSlopeXAnalysisEnum()
-
-macro=StringToEnum('SurfaceSlopeXAnalysis');
Index: sm/trunk/src/m/enum/SurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeYAnalysisEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SurfaceSlopeYAnalysisEnum()
-%SURFACESLOPEYANALYSISENUM - Enum of SurfaceSlopeYAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SurfaceSlopeYAnalysisEnum()
-
-macro=StringToEnum('SurfaceSlopeYAnalysis');
Index: sm/trunk/src/m/enum/TemperatureOldEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureOldEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TemperatureOldEnum()
-%TEMPERATUREOLDENUM - Enum of TemperatureOld
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=TemperatureOldEnum()
-
-macro=StringToEnum('TemperatureOld');
Index: /issm/trunk/src/m/enum/ThermalNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalNumRequestedOutputsEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/ThermalNumRequestedOutputsEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=ThermalNumRequestedOutputsEnum()
+%THERMALNUMREQUESTEDOUTPUTSENUM - Enum of ThermalNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalNumRequestedOutputsEnum()
+
+macro=StringToEnum('ThermalNumRequestedOutputs');
Index: /issm/trunk/src/m/enum/ThermalRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalRequestedOutputsEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/ThermalRequestedOutputsEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=ThermalRequestedOutputsEnum()
+%THERMALREQUESTEDOUTPUTSENUM - Enum of ThermalRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalRequestedOutputsEnum()
+
+macro=StringToEnum('ThermalRequestedOutputs');
Index: /issm/trunk/src/m/enum/TransientIsdamageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsdamageEnum.m	(revision 16560)
+++ /issm/trunk/src/m/enum/TransientIsdamageEnum.m	(revision 16560)
@@ -0,0 +1,11 @@
+function macro=TransientIsdamageEnum()
+%TRANSIENTISDAMAGEENUM - Enum of TransientIsdamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsdamageEnum()
+
+macro=StringToEnum('TransientIsdamage');
Index: sm/trunk/src/m/enum/TriaP1ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriaP1ElementResultEnum.m	(revision 16559)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TriaP1ElementResultEnum()
-%TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=TriaP1ElementResultEnum()
-
-macro=StringToEnum('TriaP1ElementResult');
Index: sm/trunk/src/m/exp/Shp2Exp.m
===================================================================
--- /issm/trunk/src/m/exp/Shp2Exp.m	(revision 16559)
+++ 	(revision )
@@ -1,35 +1,0 @@
-function Shp2Exp(expfilename,shapefilename)
-%SHP2EXP- transform shape file to Argus .exp file
-%
-%   Usage:
-%      Shp2Exp(expfilename,shapefilename);
-%
-%   Example:
-%      Shp2Exp('Domain.exp','Domain.shp');
-%
-%   See also EXPMASTER, EXPDOC
-
-
-	if ~exist(shapefilename,'file'),
-		error(['Shapefile ' shapefilename ' does not exist']);
-	end
-	shp=shaperead(shapefilename);
-
-	exp=struct([]);
-	for i=1:length(shp),
-		if strcmpi(shp(i).Geometry,'Polygon'),
-			x=shp(i).X; y=shp(i).Y;
-			ids=find(isnan(x));
-			x(ids)=[]; y(ids)=[];
-			
-			exp(end+1).x=x;
-			exp(end).y=y;
-			exp(end).nods=length(x);
-			exp(end).density=1;
-			exp(end).closed=1;
-			exp(end).name=num2str(shp(i).id);
-		end
-	end
-
-	expwrite(exp,expfilename);
-
Index: /issm/trunk/src/m/exp/contourlevelzero.m
===================================================================
--- /issm/trunk/src/m/exp/contourlevelzero.m	(revision 16560)
+++ /issm/trunk/src/m/exp/contourlevelzero.m	(revision 16560)
@@ -0,0 +1,199 @@
+function contours=contourlevelzero(md,mask,level)
+%CONTOURLEVELZERO - figure out the zero level (or offset thereof, specified by the level value) 
+%                   of a vectorial mask, and vectorialize it into an exp or shp compatible 
+%structure.
+%
+%   Usage:
+%      contours=contourlevelzero(md,mask,level)
+%
+%   See also: PLOT_CONTOUR
+
+%process data 
+if md.mesh.dimension==3,
+	error('contourlevelzero error message: routine not supported for 3d meshes, project on a layer');
+end
+
+x=md.mesh.x;
+y=md.mesh.y;
+index=md.mesh.elements;
+
+if isempty(mask), error('mask provided is empty'); end
+	if length(mask)~=md.mesh.numberofvertices, error('mask provided should be specified at the vertices of the mesh'); end
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=mask(Seg1);
+Data2=mask(Seg2);
+Data3=mask(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+%find the segments that contain this value
+pos1=(Range1(:,1)<level & Range1(:,2)>level);
+pos2=(Range2(:,1)<level & Range2(:,2)>level);
+pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+%get elements
+poselem12=(pos1 & pos2);
+poselem13=(pos1 & pos3);
+poselem23=(pos2 & pos3);
+poselem=find(poselem12 | poselem13 | poselem23);
+numelems=length(poselem);
+
+%if no element has been flagged, skip to the next level
+if numelems==0,
+	warning('contourlevelzero warning message: no elements found with corresponding level value in mask');
+	contours=struct([]);
+	return;
+end
+
+%go through the elements and build the coordinates for each segment (1 by element)
+x1=zeros(numelems,1);
+x2=zeros(numelems,1);
+y1=zeros(numelems,1);
+y2=zeros(numelems,1);
+edge_l=zeros(numelems,2);
+
+for j=1:numelems,
+
+	weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+	weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+	weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+	if poselem12(poselem(j));
+
+		x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+		x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+		y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+		y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+		edge_l(j,1)=Seg1_num(poselem(j));
+		edge_l(j,2)=Seg2_num(poselem(j));
+
+	elseif poselem13(poselem(j)),
+
+		x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+		x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+		y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+		y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+		edge_l(j,1)=Seg1_num(poselem(j));
+		edge_l(j,2)=Seg3_num(poselem(j));
+
+	elseif poselem23(poselem(j)),
+
+		x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+		x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+		y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+		y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+		edge_l(j,1)=Seg2_num(poselem(j));
+		edge_l(j,2)=Seg3_num(poselem(j));
+	else
+		%it shoud not go here
+	end
+end
+
+%now that we have the segments, we must try to connect them...
+
+%loop over the subcontours
+contours=struct([]);
+
+while ~isempty(edge_l),
+
+	%take the right edge of the second segment and connect it to the next segments if any
+	e1=edge_l(1,1);   e2=edge_l(1,2);
+	xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+	%erase the lines corresponding to this edge
+	edge_l(1,:)=[];
+	x1(1)=[]; x2(1)=[];
+	y1(1)=[]; y2(1)=[];
+
+	[ro1,co1]=find(edge_l==e1);
+
+	while ~isempty(ro1)
+
+		if co1==1,
+			xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+			%next edge:
+			e1=edge_l(ro1,2);
+
+		else
+			xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+			%next edge:
+			e1=edge_l(ro1,1);
+		end
+
+		%erase the lines of this
+		edge_l(ro1,:)=[];
+		x1(ro1)=[]; x2(ro1)=[];
+		y1(ro1)=[]; y2(ro1)=[];
+
+		%next connection
+		[ro1,co1]=find(edge_l==e1);
+	end
+
+	%same thing the other way (to the right)
+	[ro2,co2]=find(edge_l==e2);
+
+	while ~isempty(ro2)
+
+		if co2==1,
+			xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+			%next edge:
+			e2=edge_l(ro2,2);
+		else
+			xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+			%next edge:
+			e2=edge_l(ro2,1);
+		end
+
+		%erase the lines of this
+		edge_l(ro2,:)=[];
+		x1(ro2)=[]; x2(ro2)=[];
+		y1(ro2)=[]; y2(ro2)=[];
+
+		%next connection
+		[ro2,co2]=find(edge_l==e2);
+	end
+
+	%save xc,yc contour: 
+	contours(end+1).x=xc;
+	contours(end).y=yc;
+	contours(end).name='';
+	contours(end).nods=length(xc);
+	contours(end).density=1;
+	contours(end).closed=0;
+
+end
Index: /issm/trunk/src/m/exp/expcontourlevelzero.m
===================================================================
--- /issm/trunk/src/m/exp/expcontourlevelzero.m	(revision 16560)
+++ /issm/trunk/src/m/exp/expcontourlevelzero.m	(revision 16560)
@@ -0,0 +1,13 @@
+function expcontourlevelzero(md,mask,level,filename)
+%EXPCONTOURLEVELZERO - write an Argus file from a structure recovered from running contourlevelzero 
+%
+%   Usage:
+%      expcontourlevelzero(md,mask,level,filename)
+% 
+%   Example:
+%      expcontourlevelzero(md,md.geometry.thickness,0, 'Level0.exp');
+%
+%   See also CONTOURLEVELZERO, EXPWRITE
+
+contours=contourlevelzero(md,mask,level);
+expwrite(contours,filename);
Index: /issm/trunk/src/m/exp/expwrite.m
===================================================================
--- /issm/trunk/src/m/exp/expwrite.m	(revision 16559)
+++ /issm/trunk/src/m/exp/expwrite.m	(revision 16560)
@@ -41,5 +41,13 @@
 	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]);
+	if isfield(a,'density'),
+		if ~isempty(a(n).density),
+			fprintf(fid,'%i %f\n',[length(a(n).x) a(n).density]);
+		else
+			fprintf(fid,'%i %f\n',[length(a(n).x) 1.]);
+		end
+	else
+		fprintf(fid,'%i %f\n',[length(a(n).x) 1.]);
+	end
 	fprintf(fid,'%s\n','# X pos Y pos');
 	fprintf(fid,'%10.10f %10.10f\n',[a(n).x(:) a(n).y(:)]');
Index: /issm/trunk/src/m/geometry/NowickiProfile.m
===================================================================
--- /issm/trunk/src/m/geometry/NowickiProfile.m	(revision 16560)
+++ /issm/trunk/src/m/geometry/NowickiProfile.m	(revision 16560)
@@ -0,0 +1,39 @@
+function [b h sea] = NowickiProfile(x),
+%NOWICKIPROFILE - Create profile at the transition zone based on Sophie Nowicki's thesis
+%
+%   Usage:
+%      [b h] = NowickiProfile(x)
+%
+%      - h = ice thickness
+%      - b = ice base
+%      - x = along flow coordinate
+
+%Constant for theoretical profile
+delta = 0.1;          % ratio of water density and ice density -1
+hg    = 1;            % ice thickness at grounding line
+sea   = hg/(1+delta); % sea level
+lamda = 0.1;          % ration of deviatoric stress and water pressure
+beta  = 5;            % friction coefficient
+ms    = 0.005;        % surface accumulation rat
+mu    = 5;            % viscosity
+q     = 0.801;        % ice mass flux
+
+%mesh parameters
+b=zeros(numel(x),1);
+h=zeros(numel(x),1);
+
+%upstream of the GL
+for i = 1:ceil(numel(x)/2)
+	ss=roots([1,4*lamda*beta,0,0,6*lamda*ms*x(i)^2+12*lamda*q*x(i)-hg^4-4*lamda*beta*hg^3]);
+	for j=1:4
+		if (real(ss(j)) > 0) && (imag(ss(j)) == 0), s(i)=ss(j); end
+	end
+	h(i) = s(i);
+	b(i) = 0.;
+end
+
+%downstream of the GL
+for i = ceil(numel(x)/2):numel(x)
+	h(i) = (x(i)/(4*(delta+1)*q)+hg^(-2))^(-0.5); % ice thickness for ice shelf from (3.1)
+	b(i) = sea-h(i)*(1/(1+delta));
+end
Index: sm/trunk/src/m/interp/PatchToVec.m
===================================================================
--- /issm/trunk/src/m/interp/PatchToVec.m	(revision 16559)
+++ 	(revision )
@@ -1,21 +1,0 @@
-function vec=PatchToVec(Patch)
-%PATCHTOVEC - converts a patch to a vector by averaging over each vertex
-%
-%   Usage:
-%      vec=PatchToVec(Patch)
-
-%if the patch is P0: we have element values, return an element vector
-switch(size(Patch.value,2)),
-	case 1,
-		vec(Patch.element)=Patch.value;
-	case 3,
-		connectivity=sparse(Patch.index(:),1,1);
-		value       =sparse(Patch.index(:),1,Patch.value(:));
-		vec=full(value./connectivity);
-	case 6,
-		connectivity=sparse(Patch.index(:),1,1);
-		value       =sparse(Patch.index(:),1,Patch.value(:));
-		vec=full(value./connectivity);
-	otherwise,
-		error('interpolation not supported yet');
-	end
Index: /issm/trunk/src/m/materials/arrhenius.m
===================================================================
--- /issm/trunk/src/m/materials/arrhenius.m	(revision 16560)
+++ /issm/trunk/src/m/materials/arrhenius.m	(revision 16560)
@@ -0,0 +1,83 @@
+function rigidity=arrhenius(temperature, waterfraction, pressure)
+%ARRHENIUS - figure out the rigidity of ice for a given temperature and waterfraction
+%
+%   rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+%   temperature is in Kelvin degrees
+%   
+%   Usage:
+%   rigidity=arrhenius(temperature, waterfraction, pressure)
+
+%variables
+T0=273.15;
+n=3.;
+beta=7.9e-8; % K Pa^-1
+R=8.314; % J mol^-1 K^-1  
+T_switch=T0-10.;
+
+if(temperature<0)
+    error('input temperature should be in Kelvin (positive)');
+end
+
+if(temperature>TMeltingPoint(pressure))
+    error('input temperature is above pressure melting point.');
+end
+
+if(isnan(waterfraction))
+    waterfraction=zeros(size(temperature));
+end
+
+if(waterfraction<0)
+    error('waterfraction is negative');
+end
+
+wf_max=.1;
+if(waterfraction>wf_max)
+    error(['waterfraction exceeds permitted maximum of ' num2str(wf_max) '.']);
+end
+
+pos=find((temperature<TMeltingPoint(pressure)) & (waterfraction>0)); % cold, wet ice
+if (length(pos)>0)
+    error('cold ice with positive waterfraction detected.');
+end
+
+    function Tm=TMeltingPoint(pressure)
+        Tm=GetThom(T0,pressure);
+    end
+    
+    function Th=GetThom(T,pressure)
+        Th=T-beta*pressure;
+    end
+
+%   values for Activation energy Q and pre-exponential constants from
+%   Grewe/Blatter 2009, p54
+
+    function A0=GetA0(T)
+        A0=zeros(size(T));
+        pos0=find(T<T_switch);
+        pos1=find(T>=T_switch);
+        A0(pos0)=3.985e-13; %Grewe Blatter 2009
+        A0(pos1)=1.916e3;
+    end
+
+    function Q=GetQa(T)
+        Q=zeros(size(T));
+        pos0=find(T<T_switch);
+        pos1=find(T>=T_switch);
+        Q(pos0)=6.e4; % J mol^-1 % Paterson 2010
+        Q(pos1)=1.39e5;
+    end
+
+    function A=GetA(T, w)
+        Qa=GetQa(T); 
+        A0=GetA0(T);
+        A=A0.*exp(-Qa./(R*T)).*(1+181.25*w);        
+    end
+    
+    function B=GetRigidity(T,w,pressure)
+        Thom=GetThom(T, pressure);
+        A=GetA(Thom, w);
+        B=1./(A.^(1/n));
+    end
+
+rigidity=GetRigidity(temperature, waterfraction, pressure);
+end
Index: /issm/trunk/src/m/mech/analyticaldamage.m
===================================================================
--- /issm/trunk/src/m/mech/analyticaldamage.m	(revision 16559)
+++ /issm/trunk/src/m/mech/analyticaldamage.m	(revision 16560)
@@ -13,17 +13,24 @@
 %								'Thomas' for a 2D ice shelf, taking into account full strain rate tensor (default)
 %		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
-%								Type 'help averaging' for more information on its usage.
-%		- 'sigmab'		: a compressive backstress term to be subtracted from the driving stress 
-%								in the damage calculation
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'sigmab'		: a-priori backstress in opposition to the driving stress.
+%								Defaults to 0 everywhere. 
+
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
 %
 %   Return values:
 %		'damage' which is truncated in the range [0,1-1e-9]
 %
-%	   'B' is the rigidity, which is equal to md.materials.rheology_B in areas outside
-%		those defined by 'mask.'  Within areas defined by 'mask,' where negative damage 
-%		is inferred, 'B' is updated to make damage equal to zero.  
+%	   'B' is the ice rigidity calculated assuming D=0 everywhere. 
 %
-%		'backstress' is the inferred backstress necessary to balance the analytical solution
-%		(keeping damage within its appropriate limits, e.g. D in [0,1]).
+%		'backstress' is the inferred backstress necessary to balance the
+%		analytical solution (keeping damage within its appropriate limits, e.g. D
+%		in [0,1]).
 %
 %   Usage:
@@ -31,5 +38,5 @@
 %
 %   Example:
-%      [damage,B,backstress]=analyticaldamage(md,'eq','Weertman2D','smoothing',2,'backstress',10e3);
+%      [damage,B,backstress]=analyticaldamage(md,'eq','Weertman2D','smoothing',2,'sigmab',10e3,'coordsys','longitudinal');
 
 % check inputs
@@ -53,60 +60,10 @@
 smoothing = getfieldvalue(options,'smoothing',0);
 sigmab = getfieldvalue(options,'sigmab',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
 if length(sigmab)==1,
 	sigmab=sigmab*ones(md.mesh.numberofelements,1);
 end
 
-% average element strain rates onto vertices
-e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts; % convert to s^-1
-e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts;
-exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts;
-eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts;
-exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts;
-
-% checks: any of e1 or e2 equal to zero?
-pos=find(e1==0);
-if any(pos==1)
-	disp('WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1');
-	e1(pos)=1e-13;
-end
-pos=find(e2==0);
-if any(pos==1)
-	disp('WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1');
-	e2(pos)=1e-13;
-end
-
-%% old method using principal strain rates {{{
-%% ex=maximum principal tensile strain rate
-%ex=e1;
-%a=e2./e1;
-%pos=find(e1<0 & e2>0); % longitudinal compression and lateral tension
-%a(pos)=e1(pos)./e2(pos);
-%ex(pos)=e2(pos);
-%pos2=find(e1<0 & e2<0 & abs(e1)<abs(e2)); % lateral and longitudinal compression
-%a(pos2)=e1(pos2)./e2(pos2);
-%ex(pos2)=e2(pos2);
-%pos3=find(e1>0 & e2>0 & abs(e1)<abs(e2)); % lateral and longitudinal tension 
-%a(pos3)=e1(pos3)./e2(pos3);
-%ex(pos3)=e2(pos3);
-%id=find(e1<0 & e2<0);
-%a(id)=-a(id); % where both strain rates are compressive, enforce negative alpha
-%
-%% }}}
-
-% new method using longitudinal strain rates defined by observed velocity vector
-velangle=atan(md.initialization.vy./md.initialization.vx);
-ex=0.5*(exx+eyy)+0.5*(exx-eyy).*cos(2*velangle)+exy.*sin(2*velangle);
-ey=exx+eyy-ex; % trace of strain rate tensor is invariant
-exy=-0.5*(exx-eyy).*sin(2*velangle)+exy.*cos(2*velangle);
-a=ey./ex;
-b=exy./ex;
-pos=find(ex<0 & ey<0);
-%length(pos)
-a(pos)=-a(pos);
-
-% a < -1 in areas of strong lateral compression or longitudinal compression
-% and theta is undefined at a = -2
-pos=find(abs((abs(a)-2))<1e-3);
-a(pos)=-2+1e-3;
+[a,b,theta,ex]=thomasparams(md,'eq',eq,'smoothing',smoothing,'coordsys',coordsys);
 
 % spreading stress
@@ -120,20 +77,5 @@
 n=averaging(md,md.materials.rheology_n,0);
 
-switch eq
-	case 'Weertman1D'
-		theta=1./8*ones(md.mesh.numberofvertices,1);
-		a=zeros(md.mesh.numberofvertices,1);
-	case 'Weertman2D'
-		theta=1./9*ones(md.mesh.numberofvertices,1);
-		a=ones(md.mesh.numberofvertices,1);
-	case 'Thomas'
-		theta=((1+a+a.^2+b.^2).^((n-1)/2))./(abs(2+a).^n);
-	otherwise
-		error('argument passed to "eq" not valid.  Type "help analyticaldamage" for usage');
-end
-
 D=1-(1+a+a.^2+b.^2).^((n-1)./(2*n))./abs(ex).^(1./n).*(T-sigmab)./B./(2+a)./sign(ex);
-
-backstress=zeros(md.mesh.numberofvertices,1);
 
 % D>1 where (2+a).*sign(ex)<0, compressive regions where high backstress needed
@@ -141,5 +83,7 @@
 D(pos)=0;
 
-% backstress to bring damage to zero
+backstress=zeros(md.mesh.numberofvertices,1);
+
+% backstress to bring D down to one 
 backstress(pos)=T(pos)-(1-D(pos)).*B(pos).*sign(ex(pos)).*(2+a(pos)).*abs(ex(pos)).^(1./n(pos))./(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos));
 
@@ -154,6 +98,8 @@
 backstress(pos)=0;
 
-% increased rigidity to bring negative damage to zero
-B(pos)=sign(ex(pos))./(2+a(pos)).*(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos)).*T(pos)./abs(ex(pos)).^(1./n(pos));
+% rigidity from Thomas relation for D=0 and backstress=0
+B=sign(ex)./(2+a).*(1+a+a.^2).^((n-1)/2./n).*T./(abs(ex).^(1./n));
+pos=find(B<0);
+B(pos)=md.materials.rheology_B(pos);
 
 damage=D;
Index: /issm/trunk/src/m/mech/backstressfrominversion.m
===================================================================
--- /issm/trunk/src/m/mech/backstressfrominversion.m	(revision 16560)
+++ /issm/trunk/src/m/mech/backstressfrominversion.m	(revision 16560)
@@ -0,0 +1,71 @@
+function backstress=backstressfrominversion(md,varargin)
+%BACKSTRESSFROMINVERSION - compute ice shelf backstress from inversion results 
+%
+%	 This routine computes backstress based on the analytical formalism of
+%	 Thomas (1973) and Borstad et al. (2013).  The model must contain inversion
+%	 results for ice rigidity.  Strain rates must also be included, either from
+%	 observed or modeled velocities.  Ice rigidity B is assumed to be
+%	 parameterized by the ice temperature in md.materials.rheology_B.
+%
+%   Available options:
+%		- 'tempmask'	: mask the inverted rigidity to be no more than
+%							appropriate for the temperature of the ice?  
+%							Boolean, defaults to false.
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values:
+%		'backstress' is the inferred backstress necessary to balance the
+%		analytical solution (keeping damage within its appropriate limits, e.g. D
+%		in [0,1]).
+%
+%   Usage:
+%      backstress=backstressfrominversion(md,options)
+%
+%   Example:
+%      backstress=backstressfrominversion(md,'smoothing',2,'coordsys','longitudinal','tempmask',true);
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if ~(md.mesh.dimension==2),
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+tempmask = getfieldvalue(options,'tempmask',false);
+
+T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness;
+n=averaging(md,md.materials.rheology_n,0);
+B=md.materials.rheology_B;
+Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar;
+
+[a0,b0,theta0,ex0]=thomasparams(md,'eq','Thomas','smoothing',smoothing,'coordsys',coordsys);
+
+if tempmask
+	Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar;
+   pos=find(Bi>md.materials.rheology_B);
+   Bi(pos)=md.materials.rheology_B(pos);
+end
+
+% analytical backstress solution
+backstress=T-Bi.*sign(ex0).*(2+a0).*abs(ex0).^(1./n)./((1+a0+a0.^2+b0.^2).^((n-1)/2./n));
+backstress(find(backstress<0))=0;
Index: /issm/trunk/src/m/mech/damagefrominversion.m
===================================================================
--- /issm/trunk/src/m/mech/damagefrominversion.m	(revision 16560)
+++ /issm/trunk/src/m/mech/damagefrominversion.m	(revision 16560)
@@ -0,0 +1,33 @@
+function damage=damagefrominversion(md)
+%DAMAGEFROMINVERSION - compute ice shelf damage from inversion results
+%
+%	This routine computes damage based on the analytical formalism of Borstad et
+%	al. (2013).  The model must contain inversion results for ice rigidity.  Ice
+%	rigidity B is assumed to be parameterized by the ice temperature in
+%	md.materials.rheology_B. 
+%
+%	Usage:
+%		damage=damagefrominversion(md)
+%
+%	Example:
+%		damage=damagefrominversion(md)
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if ~(md.mesh.dimension==2),
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+damage=zeros(md.mesh.numberofvertices,1);
+% Damage where Bi softer than B(T)
+pos=find(md.results.StressbalanceSolution.MaterialsRheologyBbar<md.materials.rheology_B);
+damage(pos)=1-md.results.StressbalanceSolution.MaterialsRheologyBbar(pos)./md.materials.rheology_B(pos);
Index: /issm/trunk/src/m/mech/robintemperature.m
===================================================================
--- /issm/trunk/src/m/mech/robintemperature.m	(revision 16560)
+++ /issm/trunk/src/m/mech/robintemperature.m	(revision 16560)
@@ -0,0 +1,42 @@
+function tprofile=robintemperature(heatflux,accumrate,thickness,surftemp,z)
+%ROBINTEMPERATURE - compute vertical temperature profile of an ice sheet (Robin, 1955)
+%
+%	This routine computes the vertical temperature profile of an 
+%	ice sheet according to the solution of Robin (1955), neglecting 
+%	friction and horizontal advection.  The solution is thus most
+%  appropriate at an ice divide.
+%
+%	The coordinate system for the solution runs from z=0 at the base 
+%	to z=H at the surface of the ice.
+%
+%	Parameters (SI units):
+%		-heatflux	Geothermal heat flux (W m^-2)
+%		-accumrate	Surface accumulation rate (m s^-1 ice equivalent)
+%		-thickness	Ice thickness (m)
+%		-surftemp	Surface temperature (K)
+%		-z				Vertical position at which to calculate temperature
+%						(z can be a scalar or a vector)
+%
+%	Returns a vector the same length as z containing the temperature in K
+%
+%	Usage:
+%		tprofile=robintemperature(heatflux,accumrate,thickness,surftemp,z)
+
+%checks
+if nargin~=5
+	help robintemperature
+	error('bad usage - wrong number of arguments.')
+end
+
+%some constants (from Holland and Jenkins, 1999)
+alphaT=1.14e-6; % thermal diffusivity (m^2 s^-1)
+c=2009; % specific heat capacity (J kg^-1 K^-1)
+rho=917; % ice density (kg m^-3)
+
+%create vertical coordinate variable
+zstar=sqrt(2*alphaT*thickness/accumrate);
+
+tprofile=surftemp+sqrt(2*thickness*pi/accumrate/alphaT)*(-heatflux)/2/rho/c.*(erf(z./zstar)-erf(thickness./zstar));
+
+% difference between surface and base temperature for check (Cuffey2010 p412):
+% tprofile-surftemp
Index: /issm/trunk/src/m/mech/thomasparams.m
===================================================================
--- /issm/trunk/src/m/mech/thomasparams.m	(revision 16560)
+++ /issm/trunk/src/m/mech/thomasparams.m	(revision 16560)
@@ -0,0 +1,147 @@
+function [alpha,beta,theta,ex]=thomasparams(md,varargin)
+%THOMASPARAMS - compute Thomas' geometric parameters for an ice shelf 
+%
+%	 This routine computes geometric parameters representing ratios between
+%	 components of the horizontal strain rate tensor for an ice shelf, as
+%	 originally developed in Thomas (1973).  The model must contain computed
+%	 strain rates, either from observed or modeled ice velocities.
+%
+%   Available options:
+%	 -'eq'			: analytical equation to use in the calculation.  Must be one of:
+%				'Thomas' for a 2D ice shelf, taking into account full strain rate
+%					tensor (default)
+%				'Weertman1D' for a confined ice shelf free to flow in one direction
+%				'Weertman2D' for an unconfined ice shelf free to spread in any direction
+%
+%	 -'smoothing'	: an integer smoothing parameter for the averaging function
+%						(default 0) Type 'help averaging' for more information on its usage.
+%
+%	 -'coordsys'	: coordinate system for calculating the strain rate
+%						components. Must be one of:
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values: 
+%
+%		'alpha' which is the ratio e_yy/e_xx between components of the strain
+%		rate tensor
+%
+%		'beta' which is the ratio e_xy/e_xx between components of the strain rate
+%		tensor
+%
+%		'theta' which is a combination of alpha and beta arising from the form of
+%		the equivalent stress
+%
+%		'exx' is the longitudinal strain rate along a coordinate system defined
+%		by 'coordsys' 
+%
+%   Usage: [alpha,beta,theta,exx]=ThomasParams(md,options)
+%
+%   Example: [alpha,beta,theta,exx]=ThomasParams(md,'eq','Thomas','smoothing',2,'coordsys','longitudinal')
+
+%some checks
+if (nargin<4)
+	help ThomasParams
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)'])
+end
+if ~(md.mesh.dimension==2)
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+eq = getfieldvalue(options,'eq','Thomas');
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+
+% average element strain rates onto vertices
+e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts; % convert to s^-1
+e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts;
+exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts;
+eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts;
+exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts;
+
+% checks: any of e1 or e2 equal to zero?
+pos=find(e1==0);
+if any(pos==1)
+	disp('WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e1(pos)=1e-13;
+end
+pos=find(e2==0);
+if any(pos==1)
+	disp('WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e2(pos)=1e-13;
+end
+
+switch coordsys
+	case 'principal'
+		b=zeros(md.mesh.numberofvertices,1);
+		ex=e1;
+		a=e2./e1;
+		pos=find(e1<0 & e2>0); % longitudinal compression and lateral tension
+		a(pos)=e1(pos)./e2(pos);
+		ex(pos)=e2(pos);
+		pos2=find(e1<0 & e2<0 & abs(e1)<abs(e2)); % lateral and longitudinal compression
+		a(pos2)=e1(pos2)./e2(pos2);
+		ex(pos2)=e2(pos2);
+		pos3=find(e1>0 & e2>0 & abs(e1)<abs(e2)); % lateral and longitudinal tension
+		a(pos3)=e1(pos3)./e2(pos3);
+		ex(pos3)=e2(pos3);
+		id=find(e1<0 & e2<0);
+		a(id)=-a(id); % where both strain rates are compressive, enforce negative alpha
+		%mask=ismember(1:md.mesh.numberofvertices,id);
+		%plotmodel(md,'data',ex,'mask',mask)
+	case 'xy'
+		ex=exx;
+		a=eyy./exx;
+		b=exy./exx;
+	case 'longitudinal'
+		% using longitudinal strain rates defined by observed velocity vector
+		velangle=atan(md.initialization.vy./md.initialization.vx);
+		pos=find(md.initialization.vx==0);
+		velangle(pos)=pi/2;
+		ex=0.5*(exx+eyy)+0.5*(exx-eyy).*cos(2*velangle)+exy.*sin(2*velangle);
+		ey=exx+eyy-ex; % trace of strain rate tensor is invariant
+		exy=-0.5*(exx-eyy).*sin(2*velangle)+exy.*cos(2*velangle);
+		a=ey./ex;
+		b=exy./ex;
+		pos=find(ex<0 & ey<0);
+		%length(pos)
+		a(pos)=-a(pos);
+	otherwise
+		error('argument passed to "coordsys" not valid');
+end
+
+% a < -1 in areas of strong lateral compression or longitudinal compression and
+% theta flips sign at a = -2
+pos=find(abs((abs(a)-2))<1e-3);
+if length(pos)>0,
+	disp(['Warning: ', num2str(length(pos)), ' vertices have alpha within 1e-3 of -2'])
+end
+a(pos)=-2+1e-3;
+
+% rheology
+n=averaging(md,md.materials.rheology_n,0);
+
+switch eq
+	case 'Weertman1D'
+		theta=1./8;
+		a=zeros(md.mesh.numberofvertices,1);
+	case 'Weertman2D'
+		theta=1./9;
+		a=ones(md.mesh.numberofvertices,1);
+	case 'Thomas'
+		theta=((1+a+a.^2+b.^2).^((n-1)/2))./(abs(2+a).^n);
+	otherwise
+		error('argument passed to "eq" not valid.  Type "help zinv" for usage');
+end
+alpha=a;
+beta=b;
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 16559)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 16560)
@@ -37,4 +37,5 @@
 %   - verbose :           level of verbosity (default is 1)
 %
+%   - vertical :          is this a 2d vertical mesh (flowband, default is 0)
 %   - rifts :             followed by an ARGUS file that prescribes the rifts
 %   - toltip :            tolerance to move tip on an existing point of the domain outline
@@ -63,6 +64,21 @@
 	%Check that file exists
 	domainfile=getfieldvalue(options,'domain');
-	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found']); end
-	domain=expread(domainfile);
+	if ischar(domainfile),
+		if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found']); end
+
+		%read domain according to its extension: 
+		[path,name,ext]=fileparts(domainfile);
+		if strcmp(ext,'.exp'),
+			domain=expread(domainfile);
+		elseif strcmp(ext,'.shp'),
+			domain=shpread(domainfile);
+		else
+			error(['bamg error message: file ' domainfile ' format not supported (.shp or .exp)']);
+		end
+	elseif isstruct(domainfile),
+		domain = domainfile;
+	else
+		error('''domain'' type not supported yet');
+	end
 
 	%Build geometry 
@@ -91,4 +107,12 @@
 		%update counter
 		count=count+nods;
+	end
+	if getfieldvalue(options,'vertical',0),
+		if numel(getfieldvalue(options,'Markers',[]))~=size(bamg_geometry.Edges,1),
+			error(['for 2d vertical mesh, ''Markers'' option is required, and should be of size ' num2str(size(bamg_geometry.Edges,1))]);
+		end
+	end
+	if numel(getfieldvalue(options,'Markers',[]))==size(bamg_geometry.Edges,1),
+		bamg_geometry.Edges(:,3)=getfieldvalue(options,'Markers');
 	end
 
@@ -307,28 +331,48 @@
 [bamgmesh_out bamggeom_out]=BamgMesher(bamg_mesh,bamg_geometry,bamg_options);
 
-% plug results onto model
+if getfieldvalue(options,'vertical',0),
+	md.mesh=mesh2dvertical;
+	md.mesh.x=bamgmesh_out.Vertices(:,1);
+	md.mesh.y=bamgmesh_out.Vertices(:,2);
+	md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+	md.mesh.edges=bamgmesh_out.IssmEdges;
+	md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+	md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+	%Fill in rest of fields:
+	md.mesh.numberofelements=size(md.mesh.elements,1);
+	md.mesh.numberofvertices=length(md.mesh.x);
+	md.mesh.numberofedges=size(md.mesh.edges,1);
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+	%Now, build the connectivity tables for this mesh.
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+else
+	% plug results onto model
+	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.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;
+end
 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.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
Index: /issm/trunk/src/m/mesh/bamgflowband.m
===================================================================
--- /issm/trunk/src/m/mesh/bamgflowband.m	(revision 16560)
+++ /issm/trunk/src/m/mesh/bamgflowband.m	(revision 16560)
@@ -0,0 +1,36 @@
+function md=bamgflowband(md,x,surf,base,varargin);
+%BAMGFLOWBAND - create flowband mesh with bamg
+%
+%   Usage:
+%      md=bamgflowband(md,x,surf,base,OPTIONS)
+%
+%      surf and bed are the surface elevation and base for each x provided
+%      x must be increasing
+%      OPTIONS are bamg options
+%
+%   Example:
+%      x =[1:100:3000];
+%      h=linspace(1000,300,numel(x));
+%      b=-917/1023*h;
+%      md=bamgflowband(model,b+h,b,'hmax',80,'vertical',1,'Markers',m);
+
+%Write expfile with domain outline
+A=struct();
+A.x=[x;flipud(x);x(1)];
+A.y=[base;flipud(surf);base(1)];
+A.nods = numel(A.x);
+
+%markers:
+m                          = ones(numel(A.x)-1,1); % base        = 1
+m(numel(x))                = 2;                    % right side  = 2
+m(numel(x)+1:2*numel(x)-1) = 3;                    % top surface = 3
+m(2*numel(x))              = 4;                    % left side   = 4
+
+%mesh domain
+md=bamg(model(),'domain',A,'vertical',1,'Markers',m,varargin{:});
+
+%Deal with vertices on bed
+md.mesh.vertexonbed=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed(find(vertexflags(md.mesh,1)))=1;
+md.mesh.vertexonsurface=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface(find(vertexflags(md.mesh,3)))=1;
Index: /issm/trunk/src/m/mesh/meshconvert.m
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.m	(revision 16559)
+++ /issm/trunk/src/m/mesh/meshconvert.m	(revision 16560)
@@ -12,11 +12,11 @@
 
 if nargin==1,
-	x=md.mesh.x;
-	y=md.mesh.y;
-	index=md.mesh.elements;
+	index = md.mesh.elements;
+	x     = md.mesh.x;
+	y     = md.mesh.y;
 else
-	x=varargin{1};
-	y=varargin{2};
-	index=varargin{3};
+	index = varargin{1};
+	x     = varargin{2};
+	y     = varargin{3};
 end
 
@@ -25,23 +25,23 @@
 
 % 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);
+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.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.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.mesh.vertexonsurface  = ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed     = ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface = ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2)) = 1;
Index: /issm/trunk/src/m/mesh/meshconvert.py
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.py	(revision 16559)
+++ /issm/trunk/src/m/mesh/meshconvert.py	(revision 16560)
@@ -18,11 +18,11 @@
 
 	if not len(args):
-		x=md.mesh.x
-		y=md.mesh.y
-		index=md.mesh.elements
+		index = md.mesh.elements
+		x     = md.mesh.x
+		y     = md.mesh.y
 	else:
-		x=args[0]
-		y=args[1]
-		index=args[2]
+		index = args[0]
+		x     = args[1]
+		y     = args[2]
 
 	#call Bamg
@@ -30,27 +30,27 @@
 
 	# plug results onto model
-	md.private.bamg=OrderedDict()
-	md.private.bamg['mesh']=bamgmesh(bamgmesh_out)
-	md.private.bamg['geometry']=bamggeom(bamggeom_out)
-	md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
-	md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
-	md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
-	md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
-	md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
-	md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
+	md.private.bamg             = OrderedDict()
+	md.private.bamg['mesh']     = bamgmesh(bamgmesh_out)
+	md.private.bamg['geometry'] = bamggeom(bamggeom_out)
+	md.mesh.x                   = bamgmesh_out['Vertices'][:,0].copy()
+	md.mesh.y                   = bamgmesh_out['Vertices'][:,1].copy()
+	md.mesh.elements            = bamgmesh_out['Triangles'][:,0:3].astype(int)
+	md.mesh.edges               = bamgmesh_out['IssmEdges'].astype(int)
+	md.mesh.segments            = bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+	md.mesh.segmentmarkers      = bamgmesh_out['IssmSegments'][:,3].astype(int)
 
 	#Fill in rest of fields:
-	md.mesh.dimension=2
-	md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
-	md.mesh.numberofvertices=numpy.size(md.mesh.x)
-	md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)
-	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
-	md.mesh.vertexonbed=numpy.ones(md.mesh.numberofvertices,bool)
-	md.mask.vertexonwater=numpy.zeros(md.mesh.numberofvertices,bool)
-	md.mesh.vertexonsurface=numpy.ones(md.mesh.numberofvertices,bool)
-	md.mesh.elementonbed=numpy.ones(md.mesh.numberofelements,bool)
-	md.mesh.elementonsurface=numpy.ones(md.mesh.numberofelements,bool)
-	md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices,bool)
-	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+	md.mesh.dimension          = 2
+	md.mesh.numberofelements   = numpy.size(md.mesh.elements,axis=0)
+	md.mesh.numberofvertices   = numpy.size(md.mesh.x)
+	md.mesh.numberofedges      = numpy.size(md.mesh.edges,axis=0)
+	md.mesh.z                  = numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonbed        = numpy.ones(md.mesh.numberofvertices,bool)
+	md.mask.vertexonwater      = numpy.zeros(md.mesh.numberofvertices,bool)
+	md.mesh.vertexonsurface    = numpy.ones(md.mesh.numberofvertices,bool)
+	md.mesh.elementonbed       = numpy.ones(md.mesh.numberofelements,bool)
+	md.mesh.elementonsurface   = numpy.ones(md.mesh.numberofelements,bool)
+	md.mesh.vertexonboundary   = numpy.zeros(md.mesh.numberofvertices,bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
 
 	return md
Index: /issm/trunk/src/m/mesh/triangle2dvertical.m
===================================================================
--- /issm/trunk/src/m/mesh/triangle2dvertical.m	(revision 16560)
+++ /issm/trunk/src/m/mesh/triangle2dvertical.m	(revision 16560)
@@ -0,0 +1,62 @@
+function md=triangle(md,domainname,resolution)
+%TRIANGLE - create model mesh using the triangle package
+%
+%   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+%   where md is a @model object, domainname is the name of an Argus domain outline file, 
+%   and resolution is a characteristic length for the mesh (same unit as the domain outline
+%   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+%
+%   Usage:
+%      md=triangle(md,domainname,resolution)
+%
+%   Examples:
+%      md=triangle(md,'DomainOutline.exp',1000);
+
+%Check that mesh was not already run, and warn user: 
+if md.mesh.numberofelements~=0,
+	choice=input('This model already has a mesh. Are you sure you want to go ahead? (y/n)','s');
+	if ~strcmp(choice,'y')
+		disp('no meshing done ... exiting');
+		return
+	end
+end
+
+area=resolution^2;
+
+%Mesh using TriMesh
+[elements,x,z,segments,segmentmarkers]=TriMesh(domainname,'',area);
+
+%check that all the created nodes belong to at least one element
+orphan=find(~ismember([1:length(x)],sort(unique(elements(:)))));
+for i=1:length(orphan),
+	disp('WARNING: removing orphans');
+	%get rid of the orphan node i
+	%update x and y
+	x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+	z=[z(1:orphan(i)-(i-1)-1); z(orphan(i)-(i-1)+1:end)];
+	%update elements
+	pos=find(elements>orphan(i)-(i-1));
+	elements(pos)=elements(pos)-1;
+	%update segments
+	pos1=find(segments(:,1)>orphan(i)-(i-1));
+	pos2=find(segments(:,2)>orphan(i)-(i-1));
+	segments(pos1,1)=segments(pos1,1)-1;
+	segments(pos2,2)=segments(pos2,2)-1;
+end
+
+%plug into md
+md.mesh=mesh2dvertical;
+md.mesh.x=x;
+md.mesh.z=z;
+md.mesh.elements=elements;
+md.mesh.segments=segments;
+md.mesh.segmentmarkers=segmentmarkers;
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
Index: /issm/trunk/src/m/os/issmstssh.m
===================================================================
--- /issm/trunk/src/m/os/issmstssh.m	(revision 16559)
+++ /issm/trunk/src/m/os/issmstssh.m	(revision 16560)
@@ -7,2 +7,3 @@
 %just use starcluster command to pipe an ssh command through
 system([starcluster() ' sshmaster ' host ' --user ' login ' ''' command '''']);
+
Index: /issm/trunk/src/m/os/starcluster.m
===================================================================
--- /issm/trunk/src/m/os/starcluster.m	(revision 16559)
+++ /issm/trunk/src/m/os/starcluster.m	(revision 16560)
@@ -5,3 +5,3 @@
 %      STARCLUSTER=STARCLUSTER()
 
-STARCLUSTER=[issmdir() '/externalpackages/python/install/bin/starcluster -c ' jplsvn '/projects/CloudComputing/starcluster.config'];
+STARCLUSTER=[issmdir() '/externalpackages/python/install/bin/starcluster -c ' jplsvn '/proj-group/CloudComputing/starcluster.config'];
Index: /issm/trunk/src/m/parameterization/setflowequation.m
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.m	(revision 16559)
+++ /issm/trunk/src/m/parameterization/setflowequation.m	(revision 16560)
@@ -71,5 +71,5 @@
 
 %Check that no L1L2 or HO or FS for 2d mesh
-if (md.mesh.dimension==2),
+if strcmp(meshtype(md.mesh),'2Dhorizontal')
 	if any(L1L2flag | FSflag | HOflag)
 		error('FS and HO elements not allowed in 2d mesh, extrude it first')
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 16559)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 16560)
@@ -49,5 +49,5 @@
 
 %view 
-if md.mesh.dimension==3 & ~exist(options,'layer'),
+if strcmp(meshtype(md.mesh),'3D') & ~exist(options,'layer'),
 	view(getfieldvalue(options,'view',3));
 else
@@ -60,5 +60,5 @@
 	eval(['axis ' getfieldvalue(options,'axis')]);
 else
-	if ((md.mesh.dimension==2) | exist(options,'layer')),
+	if strcmpi(meshtype(md.mesh),'2Dhorizontal') | exist(options,'layer'),
 		axis tight equal;
 	else
@@ -253,5 +253,5 @@
 			linewidthi=linewidth{i};
 		end
-		expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+		expdisp(filenamei,gcf,stylei,linewidthi,getfieldvalue(options,'unit',1));
 	end
 end
Index: /issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.py	(revision 16559)
+++ /issm/trunk/src/m/plot/applyoptions.py	(revision 16560)
@@ -123,5 +123,11 @@
 	#view
 
-	#axis
+	#axis {{{
+	if options.exist('axis'):
+		if options.getfieldvalue('axis',True)=='off':
+			p.gca().ticklabel_format(style='plain')
+			p.setp(p.gca().get_xticklabels(), visible=False)
+			p.setp(p.gca().get_yticklabels(), visible=False)
+	# }}}
 
 	#box
@@ -164,6 +170,17 @@
 
 	#colorbar {{{
-	if options.getfieldvalue('colorbar','off')==1:
-		cb=p.colorbar()
+	if options.getfieldvalue('colorbar',1)==1:
+		if options.exist('clim'):
+			# build custom colorbar (does not yet allow customizing the location)
+			fig = p.gcf()
+			ax = p.gca()
+			divider = make_axes_locatable(ax)
+			cax = divider.new_horizontal("5%", pad=0.05, axes_class=maxes.Axes)
+			fig.add_axes(cax) 
+			cmap = mpl.cm.jet
+			norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
+			cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
+		else:
+			cb=p.colorbar()
 		cb.locator=MaxNLocator(nbins=5) # default 5 ticks
 		cb.update_ticks()
Index: /issm/trunk/src/m/plot/plot_contour.m
===================================================================
--- /issm/trunk/src/m/plot/plot_contour.m	(revision 16559)
+++ /issm/trunk/src/m/plot/plot_contour.m	(revision 16560)
@@ -11,4 +11,5 @@
 options=removefield(options,'log',0);
 [data datatype]=processdata(md,datain,options);
+if isempty(data), error('data provided is empty'); end
 
 %check is2d
@@ -225,5 +226,9 @@
 			hold on      
 		else
-			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth)];
+			dist = 5000;
+			if (max(xc)-min(xc)+max(yc)-min(yc))<dist, continue; end
+			h=patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth);
+			c = horzcat([level, xc'; length(xc), yc']);
+			clabel(c,h,'FontSize',10,'labelspacing',20000,'color',color);
 			hold on
 		end
@@ -231,5 +236,5 @@
 		% Update the CS data structure as per "contours.m"
 		% so that clabel works
-		c = horzcat(c,[level, xc'; length(xc), yc']);
+		%c = horzcat(c,[level, xc'; length(xc), yc']);
 
 	end
@@ -241,5 +246,6 @@
 		clabel(c,h);
 	else
-		clabel(c,h,'color',color,'FontSize',14);
-	end
-end
+		%clabel(c,h,'color',color,'FontSize',10,'labelspacing',20000);
+		clabel(c,h,'FontSize',10,'labelspacing',20000);
+	end
+end
Index: /issm/trunk/src/m/plot/plot_overlay.m
===================================================================
--- /issm/trunk/src/m/plot/plot_overlay.m	(revision 16559)
+++ /issm/trunk/src/m/plot/plot_overlay.m	(revision 16560)
@@ -3,5 +3,5 @@
 %
 %   Usage:
-%      plot_overlay(md,options,plotlines,plotcols,i)
+%      plot_overlay(md,data,options,plotlines,plotcols,i)
 %
 %   See also: PLOTMODEL
Index: /issm/trunk/src/m/plot/plot_unit.m
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.m	(revision 16559)
+++ /issm/trunk/src/m/plot/plot_unit.m	(revision 16560)
@@ -57,33 +57,4 @@
 		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']);
Index: /issm/trunk/src/m/plot/processdata.m
===================================================================
--- /issm/trunk/src/m/plot/processdata.m	(revision 16559)
+++ /issm/trunk/src/m/plot/processdata.m	(revision 16560)
@@ -17,4 +17,15 @@
 end
 
+%Process NaN if any (do not know before mask is applied)
+if exist(options,'nan')
+	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+end
+
+%special case for mesg 2dvertical
+if strcmp(meshtype(md.mesh),'2Dvertical'),
+	[data datatype] = processdata(md.mesh,md,data,options);
+	return;
+end
+
 %needed later on
 if isprop(md.mesh,'numberofvertices2d'), 
@@ -26,99 +37,72 @@
 end
 
-%Process Patch
-if isstruct(data) 
-	if (isprop(data,'index') & isprop(data,'value')),
-		if data.interpolation(1)==P1Enum(),
-			data=data.value;
-			data=data';
-			data=data(:);
-			datatype=4;
-		elseif data.interpolation(1)==P0Enum(),
-			data=data.value;
-			datatype=5;
-		else
-			error(['interpolation ' data.interpolation(1) ' not supported yet']);
-		end
-	else
-		error('structure other than Patch not supported yet');
-	end
-else
-	%initialize datatype
-	datatype=0;
-end
+%initialize datatype
+datatype=0;
 
 %get datasize
 datasize=size(data);
 
-%Process NaN if any (do not know before mask is applied)
-if exist(options,'nan')
-	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+%transpose data if necessary
+if (size(data,2) > size(data,1)),
+	data=data';
 end
-%non patch processing
-if datatype~=4 & datatype~=5,
+datasize=size(data);
 
-	%transpose data if necessary
-	if (size(data,2) > size(data,1)),
-		data=data';
-	end
-	datasize=size(data);
+%convert to double if necessary
+if ~isnumeric(data);
+	disp('processdata info message: data is not numeric (logical?). Converted to double');
+	data=double(data);
+end
 
-	%convert to double if necessary
-	if ~isnumeric(data);
-		disp('processdata info message: data is not numeric (logical?). Converted to double');
-		data=double(data);
-	end
+%check length
+if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (md.mesh.dimension==3 & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
+	error('plotmodel error message: data not supported yet');
+end
 
-	%check length
-	if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (md.mesh.dimension==3 & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
-		error('plotmodel error message: data not supported yet');
-	end
+%quiver?
+if datasize(2)>1,
+	datatype=3;
 
-	%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
+	%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
+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)=6*nodes
+if datasize(1)==6*md.mesh.numberofvertices
+	%keep the only norm of data
+	data1=data(1:6:md.mesh.numberofvertices*6,:);
+	data2=data(2:6:md.mesh.numberofvertices*6,:);
+	data=sqrt(data1.^2+data2.^2);
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
+end
 
-	%treat the case datasize(1)=nodes2d
-	if (md.mesh.dimension==3 & datasize(1)==numberofvertices2d),
-		data=project3d(md,'vector',data,'type','node');
-		datasize(1)=md.mesh.numberofvertices;
-		%---> go to node data
-	end
+%treat the case datasize(1)=nodes2d
+if (md.mesh.dimension==3 & datasize(1)==numberofvertices2d),
+	data=project3d(md,'vector',data,'type','node');
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
+end
 
-	%treat the case datasize(1)=nodes2d
-	if (md.mesh.dimension==3 & datasize(1)==numberofelements2d),
-		data=project3d(md,'vector',data,'type','element');
-		datasize(1)=md.mesh.numberofelements;
-		%---> go to node data
-	end
+%treat the case datasize(1)=nodes2d
+if (md.mesh.dimension==3 & datasize(1)==numberofelements2d),
+	data=project3d(md,'vector',data,'type','element');
+	datasize(1)=md.mesh.numberofelements;
+	%---> go to node data
+end
 
-	%smoothing?
-	if exist(options,'smooth')
-		data=averaging(md,data,getfieldvalue(options,'smooth'));
-		datasize(1)=md.mesh.numberofvertices;
-		%---> go to node data
-	end
+%smoothing?
+if exist(options,'smooth')
+	data=averaging(md,data,getfieldvalue(options,'smooth'));
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
 end
 
Index: /issm/trunk/src/m/plot/processmesh.m
===================================================================
--- /issm/trunk/src/m/plot/processmesh.m	(revision 16559)
+++ /issm/trunk/src/m/plot/processmesh.m	(revision 16560)
@@ -15,68 +15,56 @@
 end
 
-if (isempty(data) | ~isstruct(data)),
-	%first load x,y, etc ... to speed up plot
+%special case for mesg 2dvertical
+if strcmp(meshtype(md.mesh),'2Dvertical'),
+	[x y z elements is2d isplanet] = processmesh(md.mesh,options);
+	return;
+end
 
-	if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
-		x=md.mesh.x;
-		if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
-		y=md.mesh.y;
-		if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+%first load x,y, etc ... to speed up plot
+if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+	x=md.mesh.x;
+	if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
+	y=md.mesh.y;
+	if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+else
+	x=md.mesh.long;
+	y=md.mesh.lat;
+end
+
+z_field=getfieldvalue(options,'z',md.mesh.z);
+if ischar(z_field),
+	z=md.(z_field);
+elseif isnumeric(z_field),
+	z=z_field;
+else
+	z=md.mesh.z;
+end
+
+if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
+elements=md.mesh.elements;
+
+%is it a 2d plot?
+if (md.mesh.dimension==2);
+	is2d=1;
+elseif (md.mesh.dimension==3),
+	if getfieldvalue(options,'layer',0)>=1,
+		is2d=1;
 	else
-		x=md.mesh.long;
-		y=md.mesh.lat;
-	end
-
-	z_field=getfieldvalue(options,'z',md.mesh.z);
-	if ischar(z_field),
-		z=md.(z_field);
-	elseif isnumeric(z_field),
-		z=z_field;
-	else
-		z=md.mesh.z;
-	end
-
-	if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
-	elements=md.mesh.elements;
-
-	%is it a 2d plot?
-	if (md.mesh.dimension==2);
-		is2d=1;
-	elseif (md.mesh.dimension==3),
-		if getfieldvalue(options,'layer',0)>=1,
-			is2d=1;
-		else
-			is2d=0;
-		end
-	else
-		error(['dim = ' num2str(md.mesh.dimension) ' not supported yet']);
-	end
-
-	%layer projection? 
-	if getfieldvalue(options,'layer',0)>=1,
-		if strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
-			error('processmesh error message: cannot work with 3D meshes for now');
-		end
-		%we modify the mesh temporarily to a 2d mesh from which the 3d mesh was extruded. 
-		x=x2d;
-		y=y2d;
-		z=zeros(size(x2d));
-		elements=elements2d;
+		is2d=0;
 	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;
+	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
 
Index: /issm/trunk/src/m/plot/radarpower.m
===================================================================
--- /issm/trunk/src/m/plot/radarpower.m	(revision 16559)
+++ /issm/trunk/src/m/plot/radarpower.m	(revision 16560)
@@ -25,4 +25,8 @@
 ylim    = getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
 posting = getfieldvalue(options,'posting',0); % 0 -> image posting default
+a = getfieldvalue(options,'overlay_adjust_a',0);
+b = getfieldvalue(options,'overlay_adjust_b',1);
+c = getfieldvalue(options,'overlay_adjust_c',0);
+d = getfieldvalue(options,'overlay_adjust_d',1);
 
 %find gdal coordinates
@@ -85,4 +89,6 @@
 		%Read in temp.tif:
 		im=imread('temp.tif','TIFF');
+		%adjust contrast and brightness
+		im=imadjust(im,[a b],[c d]);
 		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
 		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
@@ -114,4 +120,6 @@
 		%Read in temp.tif:
 		im=imread('temp.tif','TIFF');
+		%adjust contrast and brightness
+		im=imadjust(im,[a b],[c d]);
 		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
 		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
@@ -144,4 +152,6 @@
 	disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
 	im=imread(overlay_image);
+	%adjust contrast and brightness
+	im=imadjust(im,[a b],[c d]);
 	im=im(toplefty:toplefty+sizey,topleftx:topleftx+sizex);
 	md.radaroverlay.pwr=double(flipud(im));
Index: /issm/trunk/src/m/regional/basinzoom.m
===================================================================
--- /issm/trunk/src/m/regional/basinzoom.m	(revision 16559)
+++ /issm/trunk/src/m/regional/basinzoom.m	(revision 16560)
@@ -38,5 +38,5 @@
 
 %Ok, find basin we are talking about: 
-load([jplsvn() '/projects/ModelData/Names/Names.mat']);
+load([jplsvn() '/ModelData/Names/Names.mat']);
 
 %Go through names: 
Index: /issm/trunk/src/m/regional/isbasin.m
===================================================================
--- /issm/trunk/src/m/regional/isbasin.m	(revision 16559)
+++ /issm/trunk/src/m/regional/isbasin.m	(revision 16560)
@@ -8,5 +8,5 @@
 
 %First, load basin names:
-load([jplsvn '/projects/ModelData/Names/Names.mat']);
+load([jplsvn '/ModelData/Names/Names.mat']);
 
 %go through names: 
Index: /issm/trunk/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 16559)
+++ /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 16560)
@@ -102,7 +102,7 @@
 	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);
+			vx=md1.results.TransientSolution(t).Vx;
+			vy=md1.results.TransientSolution(t).Vy;
+			thickness=md1.results.TransientSolution(t).Thickness;
 			spcx=[spcx InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
 			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vy,md2.mesh.x,md2.mesh.y)];
Index: /issm/trunk/src/m/shp/Shp2Exp.m
===================================================================
--- /issm/trunk/src/m/shp/Shp2Exp.m	(revision 16560)
+++ /issm/trunk/src/m/shp/Shp2Exp.m	(revision 16560)
@@ -0,0 +1,33 @@
+function Shp2Exp(expfilename,shapefilename)
+%SHP2EXP- transform shape file to Argus .exp file
+%
+%   Usage:
+%      Shp2Exp(expfilename,shapefilename);
+%
+%   Example:
+%      Shp2Exp('Domain.exp','Domain.shp');
+%
+%   See also EXPMASTER, EXPDOC
+
+	if ~exist(shapefilename,'file'),
+		error(['Shapefile ' shapefilename ' does not exist']);
+	end
+	shp=shaperead(shapefilename);
+
+	exp=struct([]);
+	for i=1:length(shp),
+		if strcmpi(shp(i).Geometry,'Polygon'),
+			x=shp(i).X; y=shp(i).Y;
+			ids=find(isnan(x));
+			x(ids)=[]; y(ids)=[];
+
+			exp(end+1).x=x;
+			exp(end).y=y;
+			exp(end).nods=length(x);
+			exp(end).density=1;
+			exp(end).closed=1;
+			exp(end).name=num2str(shp(i).id);
+		end
+	end
+
+	expwrite(exp,expfilename);
Index: /issm/trunk/src/m/shp/shpdisp.m
===================================================================
--- /issm/trunk/src/m/shp/shpdisp.m	(revision 16560)
+++ /issm/trunk/src/m/shp/shpdisp.m	(revision 16560)
@@ -0,0 +1,52 @@
+function shpdisp(domainoutline,varargin)
+%SHPDISP - plot the contours of a domain outline file
+%
+%   This routine reads in a domain outline file (Shape format) and plots all the contours 
+%
+%   Usage:
+%      shpdisp(domainoutline,varargin)
+%      shpdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%
+%   Example:
+%      shpdisp('Domain.shp',1,'--r',2,10^3);
+%
+%   See also SHPREAD, SHPDOC
+
+%check nargin
+if ~nargin | nargin>5
+	help shpdisp
+	error('shpdisp error message: bad usage');
+end
+
+%parse input
+if nargin<=1,
+	figurenumber=1;
+else
+	figurenumber=varargin{1};
+end
+if nargin<=2
+	linestyle='r-';
+else
+	linestyle=varargin{2};
+end
+if nargin<=3
+	linewidth=1;
+else
+	linewidth=varargin{3};
+end
+if nargin<=4
+	unitmultiplier=1;
+else
+	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
+end
+
+domain=shpread(domainoutline);
+
+figure(figurenumber),hold on
+for i=1:length(domain),
+	if (isnumeric(linestyle))
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+	else
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+	end
+end
Index: /issm/trunk/src/m/shp/shpread.m
===================================================================
--- /issm/trunk/src/m/shp/shpread.m	(revision 16560)
+++ /issm/trunk/src/m/shp/shpread.m	(revision 16560)
@@ -0,0 +1,57 @@
+function Struct=shpread(filename)
+%SHPREAD - read a shape file and build a Structure
+%
+%   This routine reads a shape file .shp and builds a Structure containing the 
+%   fields x and y corresponding to the coordinates, one for the filename of
+%   the shp file, for the density, for the nodes, and a field closed to 
+%   indicate if the domain is closed. 
+%   The first argument is the .shp file to be read and the second one (optional) 
+%   indicates if the last point shall be read (1 to read it, 0 not to).
+%
+%   Usage:
+%      Struct=shpread(filename)
+%
+%   Example:
+%      Struct=shpread('domainoutline.shp')
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['shpread error message: file ' filename ' not found!']);
+end
+
+%initialize number of profile
+count=0;
+
+%read shapefile
+shp=shaperead(filename);
+
+Struct=struct([]);
+fields=fieldnames(shp);
+for i=1:length(shp),
+	if strcmpi(shp(i).Geometry,'Polygon'),
+		x=shp(i).X'; y=shp(i).Y';
+		ids=find(isnan(x));
+		x(ids)=[]; y(ids)=[];
+
+		Struct(end+1).x=x;
+		Struct(end).y=y;
+		Struct(end).nods=length(x);
+		Struct(end).density=1;
+		Struct(end).closed=1;
+		if isfield(shp,'id'),
+			Struct(end).name=num2str(shp(i).id);
+		else
+			Struct(end).name='';
+		end
+		for j=1:length(fields),
+			field=fields{j};
+			if ~(strcmpi(field,'X') | strcmpi(field,'Y') | strcmpi(field,'id')),
+				Struct(end).(field)=shp(i).(field);
+			end
+		end
+	end
+end
+
+end
Index: /issm/trunk/src/m/shp/shpwrite.m
===================================================================
--- /issm/trunk/src/m/shp/shpwrite.m	(revision 16560)
+++ /issm/trunk/src/m/shp/shpwrite.m	(revision 16560)
@@ -0,0 +1,26 @@
+function shpwrite(shp,filename)
+%SHPWRITE - write a shape file from a contour structure
+%
+%   Usage:
+%      shpwrite(shp,filename)
+%
+%   Example:
+%      shpwrite(shp,'domainoutline.shp')
+%
+%   See also SHPREAD
+
+
+%initialize number of profile
+count=0;
+
+
+contours=struct([]);
+for i=1:length(shp),
+	contours(i).Geometry='Polygon';
+	contours(i).id=i;
+	contours(i).X=shp(i).x;
+	contours(i).Y=shp(i).y;
+end
+	
+shapewrite(contours,filename);
+end
Index: sm/trunk/src/m/solve/MatlabProcessPatch.m
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.m	(revision 16559)
+++ 	(revision )
@@ -1,65 +1,0 @@
-function structure=MatlabProcessPatch(structure)
-%PROCESSPATCH - create a structure from a patch
-%
-%   Usage:
-%      Result=ProcessPatch(Result);
-
-%return if there is no field Patch
-if (~isfield(structure,'Patch')),
-	return;
-end
-
-%loop over steps
-for i=1:length(structure),
-
-	%Get Patch for current step
-	Patch=structure(i).Patch;
-	numvertices=structure(i).PatchVertices;
-
-	%check that Patch is not empty
-	if length(Patch)==0 continue; end
-
-	%Get number of fields;
-	fields=unique(Patch(:,1));
-	steps=unique(Patch(:,2));
-
-	%parse steps
-	for j=1:length(steps),
-
-		posstep=find(Patch(:,2)==steps(j));
-
-		%Take all the lines of the Patch for this timestep
-		temporarypatch=Patch(posstep,:);
-		time=temporarypatch(1,3);
-		step=temporarypatch(1,2);
-
-		%parse fields
-		for i=1:length(fields),
-
-			%get name
-			fieldname=EnumToString(fields(i));
-
-			%get line positions
-			pos=find(temporarypatch(:,1)==fields(i));
-
-			%Fill Result structure
-			structure(step).steps=step;
-			structure(step).time=time;
-			structure(step).(fieldname).element=temporarypatch(pos,4);
-			structure(step).(fieldname).interpolation=temporarypatch(pos,5);
-			structure(step).(fieldname).index=temporarypatch(pos,6:5+numvertices);
-			if structure(step).(fieldname).interpolation==P1Enum(),
-				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices:end);
-			end
-			if structure(step).(fieldname).interpolation==P0Enum(),
-				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices);
-			end
-
-		end
-	end
-end
-
-%remove fields
-structure=rmfield(structure,'Patch');
-structure=rmfield(structure,'PatchVertices');
-structure=rmfield(structure,'PatchNodes');
Index: sm/trunk/src/m/solve/MatlabProcessPatch.py
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.py	(revision 16559)
+++ 	(revision )
@@ -1,19 +1,0 @@
-def MatlabProcessPatch(structure):
-	"""
-	PROCESSPATCH - create a structure from a patch
- 
-	   Usage:
-	      Result=ProcessPatch(Result);
-	"""
-
-	#loop over steps
-	for structurei in structure:
-
-		#return if there is no field Patch
-		if not hasattr(structurei,'Patch'):
-			continue
-
-		raise SystemError("MatlabProcessPatch not implemented in Python.")
-
-	return structure
-
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 16559)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 16560)
@@ -200,4 +200,8 @@
 	%first get length of string array: 
 	num=numel(data);
+	if isnumeric(data) & num==1 & isnan(data),
+		num = 0;
+	end
+
 	%now get length of record: 
 	recordlength=4+4; %for length of array + code
Index: /issm/trunk/src/m/solve/marshall.m
===================================================================
--- /issm/trunk/src/m/solve/marshall.m	(revision 16559)
+++ /issm/trunk/src/m/solve/marshall.m	(revision 16560)
@@ -39,4 +39,7 @@
 end
 
+%Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',true,'format','Boolean');
+
 %close file
 st=fclose(fid);
Index: /issm/trunk/src/m/solve/marshall.py
===================================================================
--- /issm/trunk/src/m/solve/marshall.py	(revision 16559)
+++ /issm/trunk/src/m/solve/marshall.py	(revision 16560)
@@ -42,4 +42,7 @@
 		exec("md.%s.marshall(md,fid)" % field)
 
+	#Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+	WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',True,'format','Boolean');
+
 	#close file
 	try:
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 16559)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 16560)
@@ -11,6 +11,4 @@
 end
 
-%process patch if necessary
-results=MatlabProcessPatch(results);
 
 function results=parseresultsfromdiskioserial(filename) % {{{
@@ -76,9 +74,5 @@
 
 	%Add result
-	if strcmpi(result.fieldname,'Patch'),
-		results(result.step).(result.fieldname)=[0 result.N];
-	else
-		results(result.step).(result.fieldname)=NaN;
-	end
+	results(result.step).(result.fieldname)=NaN;
 
 	%read next result
@@ -90,19 +84,6 @@
 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
 
@@ -117,14 +98,5 @@
 
 	%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
+	results(result.step).(result.fieldname)=result.field;
 
 	%read next result
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 16559)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 16560)
@@ -4,5 +4,4 @@
 import results as resultsclass
 from MatlabFuncs import *
-from MatlabProcessPatch import *
 
 def parseresultsfromdisk(filename,iosplit):
@@ -18,7 +17,4 @@
 	else:
 		results=parseresultsfromdiskioserial(filename)
-
-	#process patch if necessary
-	results=MatlabProcessPatch(results)
 
 	return results
@@ -96,8 +92,5 @@
 
 		#Add result
-		if strcmpi(result['fieldname'],'Patch'):
-			setattr(results[result['step']-1],result['fieldname'],[0,result['N']])
-		else:
-			setattr(results[result['step']-1],result['fieldname'],float('NaN'))
+		setattr(results[result['step']-1],result['fieldname'],float('NaN'))
 
 		#read next result
@@ -109,17 +102,6 @@
 	while result:
 
-		#Add result
-		if strcmpi(result['fieldname'],'Patch'):
-			patchdimensions=getattr(results[result['step']-1],result['fieldname'])
-			setattr(results[result['step']-1],result['fieldname'],[patchdimensions[0]+result['M'],result['N']])
-
 		#read next result
 		result=ReadDataDimensions(fid)
-
-	#allocate patches
-	for result in results.itervalues():
-		if 'Patch' in result:
-			setattr(result,'Patch',numpy.zeros((result['Patch'][0],result['Patch'][1])))
-			setattr(result,'counter',0)    #use to index into the patch
 
 	#third pass, this time to read the real information
@@ -137,12 +119,5 @@
 
 		#Add result
-		if strcmpi(result['fieldname'],'Patch'):
-			counter=results[result['step']-1].counter
-			counter2=counter+result['field'].shape[0]-1
-			getattr(results[result['step']-1],result['fieldname'])[counter:counter2,:]=result['field']
-			#increment counter: 
-			results[result['step']-1].counter=counter2+1
-		else:
-			setattr(results[result['step']-1],result['fieldname'],result['field'])
+		setattr(results[result['step']-1],result['fieldname'],result['field'])
 
 		#read next result
Index: /issm/trunk/src/m/solve/process_solve_options.m
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.m	(revision 16559)
+++ /issm/trunk/src/m/solve/process_solve_options.m	(revision 16560)
@@ -10,8 +10,8 @@
 solution_type=getfieldvalue(options,'solution_type');
 if ~ismember(solution_type,[StressbalanceSolutionEnum(),MasstransportSolutionEnum(),ThermalSolutionEnum(),...
-		SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),...
+		SteadystateSolutionEnum(),TransientSolutionEnum(),...
 		BalancethicknessSolutionEnum(),BalancethicknessSoftSolutionEnum(),...
 		BalancevelocitySolutionEnum(),BedSlopeSolutionEnum(),...
-		SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum()]),
+		SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum(),DamageEvolutionSolutionEnum()]),
 	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
 end
Index: /issm/trunk/src/m/solve/process_solve_options.py
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.py	(revision 16559)
+++ /issm/trunk/src/m/solve/process_solve_options.py	(revision 16560)
@@ -19,5 +19,5 @@
 	solution_type=options.getfieldvalue('solution_type')
 	if solution_type not in (StressbalanceSolutionEnum(),MasstransportSolutionEnum(),ThermalSolutionEnum(),\
-			SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),\
+			SteadystateSolutionEnum(),TransientSolutionEnum(),\
 			BalancethicknessSolutionEnum(),BalancevelocitySolutionEnum(),\
 			BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),\
Index: /issm/trunk/src/m/solvers/issmgslsolver.m
===================================================================
--- /issm/trunk/src/m/solvers/issmgslsolver.m	(revision 16560)
+++ /issm/trunk/src/m/solvers/issmgslsolver.m	(revision 16560)
@@ -0,0 +1,15 @@
+function issmoptions=issmgslsolver(varargin)
+%ISSMSOLVER - 
+%
+%   Usage:
+%      options=issmsolver;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+issmoptions=struct();
+
+%default issmoptions options
+issmoptions.toolkit='issm';
+issmoptions.mat_type=getfieldvalue(options,'mat_type','dense');
+issmoptions.vec_type=getfieldvalue(options,'vec_type','seq');
+issmoptions.solver_type=getfieldvalue(options,'solver_type','gsl');
Index: /issm/trunk/src/m/solvers/issmgslsolver.py
===================================================================
--- /issm/trunk/src/m/solvers/issmgslsolver.py	(revision 16560)
+++ /issm/trunk/src/m/solvers/issmgslsolver.py	(revision 16560)
@@ -0,0 +1,28 @@
+from pairoptions import *
+def issmgslsolver(*args):
+	#ISSMSOLVE - return issm solver options
+	#
+	#   Usage:
+	#      options=issmsolver;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['toolkit','issm'],['mat_type','dense'],['vec_type','seq'],['solver_type','gsl']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/issmmumpssolver.m
===================================================================
--- /issm/trunk/src/m/solvers/issmmumpssolver.m	(revision 16560)
+++ /issm/trunk/src/m/solvers/issmmumpssolver.m	(revision 16560)
@@ -0,0 +1,15 @@
+function issmoptions=issmmumpssolver(varargin)
+%ISSMSOLVER - 
+%
+%   Usage:
+%      options=issmsolver;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+issmoptions=struct();
+
+%default issmoptions options
+issmoptions.toolkit='issm';
+issmoptions.mat_type=getfieldvalue(options,'mat_type','mpisparse');
+issmoptions.vec_type=getfieldvalue(options,'vec_type','mpi');
+issmoptions.solver_type=getfieldvalue(options,'solver_type','mumps');
Index: /issm/trunk/src/m/solvers/issmmumpssolver.py
===================================================================
--- /issm/trunk/src/m/solvers/issmmumpssolver.py	(revision 16560)
+++ /issm/trunk/src/m/solvers/issmmumpssolver.py	(revision 16560)
@@ -0,0 +1,28 @@
+from pairoptions import *
+def issmmumpssolver(*args):
+	#ISSMSOLVE - return issm solver options
+	#
+	#   Usage:
+	#      options=issmsolver;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi'],['solver_type','mumps']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: sm/trunk/src/m/solvers/issmsolver.m
===================================================================
--- /issm/trunk/src/m/solvers/issmsolver.m	(revision 16559)
+++ 	(revision )
@@ -1,14 +1,0 @@
-function issmoptions=issmsolver(varargin)
-%ISSMSOLVER - 
-%
-%   Usage:
-%      options=issmsolver;
-
-%retrieve options provided in varargin
-options=pairoptions(varargin{:});
-issmoptions=struct();
-
-%default issmoptions options
-issmoptions.toolkit='issm';
-issmoptions.mat_type=getfieldvalue(options,'mat_type','mpidense');
-issmoptions.vec_type=getfieldvalue(options,'vec_type','mpi');
Index: sm/trunk/src/m/solvers/issmsolver.py
===================================================================
--- /issm/trunk/src/m/solvers/issmsolver.py	(revision 16559)
+++ 	(revision )
@@ -1,28 +1,0 @@
-from pairoptions import *
-def asmoptions(*args):
-	#ISSMSOLVE - return issm solver options
-	#
-	#   Usage:
-	#      options=issmsolver;
-	
-	#retrieve options provided in varargin
-	arguments=pairoptions(*args) 
-	
-	options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi']];
-
-	#now, go through our arguments, and write over default options.
-	for i in range(len(arguments.list)):
-		arg1=arguments.list[i][0]
-		arg2=arguments.list[i][1]
-		found=0;
-		for j in range(len(options)):
-			joption=options[j][0]
-			if joption==arg1:
-				joption[1]=arg2;
-				options[j]=joption;
-				found=1;
-				break
-		if not found:
-			#this option did not exist, add it: 
-			options.append([arg1,arg2])
-	return options
Index: /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp
===================================================================
--- /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 16559)
+++ /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 16560)
@@ -55,4 +55,18 @@
 		#endif
 	}
+	else if(strcmp(name,"_HAVE_GSL_")==0){
+		#ifdef _HAVE_GSL_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_TAO_")==0){
+		#ifdef _HAVE_TAO_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
 	else if(strcmp(name,"_HAVE_PETSC_")==0){
 		#ifdef _HAVE_PETSC_
@@ -83,4 +97,29 @@
 		xMemCpy<char>(svalue,ISSM_PREFIX,(strlen(ISSM_PREFIX)+1));
 	}
+	else if(strcmp(name,"PACKAGE_NAME")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_NAME)+1);
+		xMemCpy<char>(svalue,PACKAGE_NAME,(strlen(PACKAGE_NAME)+1));
+	}
+	else if(strcmp(name,"PACKAGE_VERSION")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_VERSION)+1);
+		xMemCpy<char>(svalue,PACKAGE_VERSION,(strlen(PACKAGE_VERSION)+1));
+	}
+	else if(strcmp(name,"PACKAGE_URL")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_URL)+1);
+		xMemCpy<char>(svalue,PACKAGE_URL,(strlen(PACKAGE_URL)+1));
+	}
+	else if(strcmp(name,"PACKAGE_BUGREPORT")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_BUGREPORT)+1);
+		xMemCpy<char>(svalue,PACKAGE_BUGREPORT,(strlen(PACKAGE_BUGREPORT)+1));
+	}
+	else if(strcmp(name,"PACKAGE_BUILD_DATE")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_BUILD_DATE)+1);
+		xMemCpy<char>(svalue,PACKAGE_BUILD_DATE,(strlen(PACKAGE_BUILD_DATE)+1));
+	}
 	else{
 		_error_("variable " << name << " not supported yet");
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 16559)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 16560)
@@ -19,9 +19,9 @@
 
 	/* required input: */
-	int     dim;
-	int     numberofelements;
-	int     numberofvertices;
-	int    *elements         = NULL;
-	int     elements_width;
+	int  meshtype;
+	int  numberofelements;
+	int  numberofvertices;
+	int *elements         = NULL;
+	int  elements_width;
 
 	int numberofelements2d;
@@ -45,20 +45,31 @@
 
 	/*Fetch data: */
-	FetchData(&dim,mxGetAssignedField(MODEL,0,"dimension"));
-	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
-	FetchData(&numberofvertices,mxGetAssignedField(MODEL,0,"numberofvertices"));
-	FetchData(&elements,NULL,&elements_width,mxGetAssignedField(MODEL,0,"elements"));
+	FetchData(&numberofelements,mxGetAssignedField(MESH,0,"numberofelements"));
+	FetchData(&numberofvertices,mxGetAssignedField(MESH,0,"numberofvertices"));
+	FetchData(&elements,NULL,&elements_width,mxGetAssignedField(MESH,0,"elements"));
 
-	if (dim==3){
-		FetchData(&numberofelements2d,mxGetAssignedField(MODEL,0,"numberofelements2d"));
-		FetchData(&numberofvertices2d,mxGetAssignedField(MODEL,0,"numberofvertices2d"));
-		FetchData(&elements2d,NULL,NULL,mxGetAssignedField(MODEL,0,"elements2d"));
+	if(strcmp(mxGetClassName(MESH),"mesh3d")==0){
+		meshtype = Mesh3DEnum;
+		FetchData(&numberofelements2d,mxGetAssignedField(MESH,0,"numberofelements2d"));
+		FetchData(&numberofvertices2d,mxGetAssignedField(MESH,0,"numberofvertices2d"));
+		FetchData(&elements2d,NULL,NULL,mxGetAssignedField(MESH,0,"elements2d"));
+		FetchData(&numberoflayers,mxGetAssignedField(MESH,0,"numberoflayers"));
 	}
-	FetchData(&numberoflayers,mxGetAssignedField(MODEL,0,"numberoflayers"));
+	else if(strcmp(mxGetClassName(MESH),"mesh2dhorizontal")==0){
+		meshtype = Mesh2DhorizontalEnum;
+		numberoflayers=1;
+	}
+	else if(strcmp(mxGetClassName(MESH),"mesh2dvertical")==0){
+		meshtype = Mesh2DverticalEnum;
+		numberoflayers=1;
+	}
+	else{
+		_error_("Mesh type "<<mxGetClassName(MESH)<<" not supported yet");
+	}
 	FetchData(&numareas,NUMAREAS);
 
 	/*Run partitioning algorithm based on a "clever" use of the Metis partitioner: */
 	MeshPartitionx(&int_element_partitioning,&int_node_partitioning,numberofelements,numberofvertices,elements,
-		numberofelements2d,numberofvertices2d,elements2d,numberoflayers,elements_width,dim,numareas);
+		numberofelements2d,numberofvertices2d,elements2d,numberoflayers,elements_width,meshtype,numareas);
 
 	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 16559)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 16560)
@@ -27,5 +27,5 @@
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define MODEL    prhs[0]
+#define MESH    prhs[0]
 #define NUMAREAS prhs[1]
 /* serial output macros: */
@@ -36,5 +36,5 @@
 #ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define MODEL    PyTuple_GetItem(args,0)
+#define MESH     PyTuple_GetItem(args,0)
 #define NUMAREAS PyTuple_GetItem(args,1)
 /* serial output macros: */
Index: /issm/trunk/src/wrappers/ShpRead/ShpRead.cpp
===================================================================
--- /issm/trunk/src/wrappers/ShpRead/ShpRead.cpp	(revision 16560)
+++ /issm/trunk/src/wrappers/ShpRead/ShpRead.cpp	(revision 16560)
@@ -0,0 +1,91 @@
+/*\file ShpRead.c
+ *\brief: shp to exp file conversion mex module.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ShpRead.h"
+#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+#include "shapefil.h"
+#endif
+
+void ShpReadUsage(void){/*{{{*/
+	_printf0_("ShpRead - Read shapefile\n");
+	_printf0_("\n");
+	_printf0_("   This module reads shapefiles and converts them to matlab/python structures\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ShpRead(filename);\n");
+	_printf0_("      filexp      file name of exp file to be written\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      ShpRead('file.shp');\n");
+}/*}}}*/
+WRAPPER(ShpRead){
+
+	/*input: */
+	char *filename= NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
+	_error_("Shapelib not available! Cannot carry out shp file translation!");
+	#else
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs != NLHS){ShpReadUsage(); _error_("ShpRead usage error");}
+	if(nrhs != NRHS){ShpReadUsage(); _error_("ShpRead usage error");}
+
+	/*Input datasets: */
+	FetchData(&filename,SHP_IN);
+
+	/*Open shapefile*/
+	SHPHandle hSHP = SHPOpen( filename, "rb" );
+	if(!hSHP) _error_("Error opening shp/shx files.");
+
+	/*read header and print out file bounds*/
+	int         nShapeType,nEntities;
+	IssmPDouble adfMinBound[4], adfMaxBound[4];
+	SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );
+	_printf_("Shapefile Type: "<<SHPTypeName(nShapeType)<<"   number of Shapes: "<< nEntities<<"\n\n");
+
+	/*Initialize output*/
+	Contours* contours = new Contours();
+
+	/*Read all objects*/
+	for(int i=0; i<nEntities;i++ ){
+
+		SHPObject* psShape = SHPReadObject(hSHP,i);
+		_printf_( "Shape #"<<i<<" ("<<SHPTypeName(psShape->nSHPType)<<") nVertices="<<psShape->nVertices<<", nParts="<<psShape->nParts<<"\n");
+
+		Contour<double> *contour = NULL;
+
+		switch(psShape->nSHPType){
+			case SHPT_ARC:
+				contour=new Contour<double>(0,psShape->nVertices,psShape->padfX,psShape->padfY,false);
+				break;
+			default:
+				_printf_("Shape type "<<SHPTypeName(psShape->nSHPType)<<"not supported yet, skipping...\n");
+		}
+
+		/*Add to contours and clean up*/
+		if(contour) contours->AddObject(contour);
+		SHPDestroyObject(psShape);
+	}
+
+	/*Write output*/
+	WriteData(SHP_OUT,contours);
+
+	/*Clean-up*/
+	delete contours;
+	xDelete<char>(filename);
+
+	#endif
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/ShpRead/ShpRead.h
===================================================================
--- /issm/trunk/src/wrappers/ShpRead/ShpRead.h	(revision 16560)
+++ /issm/trunk/src/wrappers/ShpRead/ShpRead.h	(revision 16560)
@@ -0,0 +1,47 @@
+/*!\file ShpRead.h
+ * \brief: prototype for shp read mex module.
+ */
+
+#ifndef _SHPREAD_H
+#define _SHPREAD_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ShpRead"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define SHP_IN  prhs[0]
+/* serial output macros: */
+#define SHP_OUT  (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define SHP_IN PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define SHP_OUT output,0
+#endif
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 16559)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 16560)
@@ -88,5 +88,5 @@
 				   Exp2Kml.la\
 				   Kml2Exp.la\
-				   Shp2Exp.la\
+				   ShpRead.la\
 				   Shp2Kml.la
 endif
@@ -269,7 +269,7 @@
 Scotch_la_LIBADD = ${deps} $(SCOTCHLIB) $(MPILIB) $(BLASLAPACKLIB)
 
-Shp2Exp_la_SOURCES = ../Shp2Exp/Shp2Exp.cpp\
-							../Shp2Exp/Shp2Exp.h
-Shp2Exp_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+ShpRead_la_SOURCES = ../ShpRead/ShpRead.cpp\
+							../ShpRead/ShpRead.h
+ShpRead_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
Index: /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h	(revision 16559)
+++ /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h	(revision 16560)
@@ -26,5 +26,5 @@
 	}\
 	catch (exception &e){\
-		mexErrMsgTxt(exprintf("Standard exception: %s\n",e.what()));\
+		mexErrMsgTxt(e.what());\
 	}\
 	catch(...){\
Index: /issm/trunk/src/wrappers/python/include/wrapper_macros.h
===================================================================
--- /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 16559)
+++ /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 16560)
@@ -31,5 +31,5 @@
   } \
 	catch (exception &e){\
-		PyErr_SetString(PyExc_TypeError,exprintf("Standard exception: %s\n",e.what()));\
+		PyErr_SetString(PyExc_TypeError,e.what());\
 		return NULL;\
 	}\
@@ -43,5 +43,4 @@
 /* WRAPPER 3.2 {{{*/
 #define WRAPPER(modulename,...)  \
-\
 static PyObject* modulename(PyObject* self,PyObject* args);\
 static PyMethodDef modulename##_funcs[] = {\
@@ -49,5 +48,4 @@
 	{NULL,NULL,0,NULL}\
 };\
-\
 static struct PyModuleDef modulename##module= {\
 	PyModuleDef_HEAD_INIT,\
@@ -58,11 +56,8 @@
 	modulename##_funcs\
 };\
-\
 PyMODINIT_FUNC PyInit_##modulename(void){\
-\
 	import_array();\
 	return PyModule_Create(&modulename##module);\
 }\
-\
 static PyObject* modulename(PyObject* self,PyObject* args)
 /*}}}*/
@@ -70,5 +65,4 @@
 /* WRAPPER 2.7 {{{*/
 #define WRAPPER(modulename,...)  \
-\
 static PyObject* modulename(PyObject* self,PyObject* args);\
 static PyMethodDef modulename##_funcs[] = {\
@@ -76,11 +70,8 @@
 	{NULL,NULL,0,NULL}\
 };\
-\
 PyMODINIT_FUNC init##modulename(void){\
-\
 	import_array();\
 	(void) Py_InitModule(#modulename, modulename##_funcs);\
 }\
-\
 static PyObject* modulename(PyObject* self,PyObject* args)
 /*}}}*/
Index: /issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/IdToName.m	(revision 16560)
@@ -66,4 +66,5 @@
 	case 237, name='SquareShelfTranIspddIsdeltaSSA3d';
 	case 270, name='SquareShelfStressSSA2dDamage';
+	case 271, name='SquareShelfStressSSA2dDamageTran';
 	case 272, name='SquareShelfCMZSSA2dDamage';
 	case 274, name='SquareShelfStressSSA2dDamageRift';
@@ -73,8 +74,8 @@
 	case 301, name='SquareSheetConstrainedStressSSA2d';
 	case 302, name='SquareSheetConstrainedStressSIA2d';
-	case 303, name='SquareSheetConstrainedStressHSSA2d';
+	case 303, name='SquareSheetConstrainedStressSIASSA2d';
 	case 304, name='SquareSheetConstrainedStressSSA3d';
 	case 305, name='SquareSheetConstrainedStressSIA3d';
-	case 306, name='SquareSheetConstrainedStressHSSA3d';
+	case 306, name='SquareSheetConstrainedStressSIASSA3d';
 	case 307, name='SquareSheetConstrainedStressHO';
 	case 308, name='SquareSheetConstrainedStressFS';
@@ -169,4 +170,6 @@
 	case 612, name='79NorthCMBalThic2dDG';
 	case 613, name='79NorthCMBalThicVxVy';
+	case 701, name='FlowbandFSshelf';
+	case 702, name='FlowbandFSsheetshelf';
 	case 1101, name='ISMIPAHO';
 	case 1102, name='ISMIPAFS';
@@ -222,4 +225,19 @@
 	case 3015, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifference';
 	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
+	case 3020, name='SquareShelfConstrainedTranAdolcReverseVsForward';
+	case 3101, name='SquareShelfConstrainedStressSSA2dAdolcMumps';
+	case 3102, name='SquareShelfConstrainedStressSSA3dAdolcMumps';
+	case 3103, name='SquareShelfConstrainedStressHOAdolcMumps';
+	case 3104, name='SquareShelfConstrainedStressFSAdolcMumps';
+	case 3105, name='SquareShelfConstrainedMasstransp2dAdolcMumps';
+	case 3106, name='SquareShelfConstrainedMasstransp2dDGAdolcMumps';
+	case 3107, name='SquareShelfConstrainedMasstransp3dAdolcMumps';
+	case 3108, name='SquareShelfConstrainedTherSteaAdolcMumps';
+	case 3109, name='SquareShelfConstrainedTherTranAdolcMumps';
+	case 3110, name='SquareShelfConstrainedTranSSA2dAdolcMumps';
+	case 3115, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps';
+	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
+	case 3120, name='SquareShelfConstrainedTranAdolcReverseVsForwardMumps';
+
 
 	otherwise, name='N/A';
Index: /issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/IdToName.py	(revision 16560)
@@ -77,8 +77,8 @@
 	301  : 'SquareSheetConstrainedStressSSA2d',
 	302  : 'SquareSheetConstrainedStressSIA2d',
-	303  : 'SquareSheetConstrainedStressHSSA2d',
+	303  : 'SquareSheetConstrainedStressSIASSA2d',
 	304  : 'SquareSheetConstrainedStressSSA3d',
 	305  : 'SquareSheetConstrainedStressSIA3d',
-	306  : 'SquareSheetConstrainedStressHSSA3d',
+	306  : 'SquareSheetConstrainedStressSIASSA3d',
 	307  : 'SquareSheetConstrainedStressHO',
 	308  : 'SquareSheetConstrainedStressFS',
@@ -226,4 +226,18 @@
 	3015 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifference',
 	3019 : 'SquareShelfConstrainedTherTranAdolcReverseVsForward',
+	3020 : 'SquareShelfConstrainedTranAdolcReverseVsForward',
+	3101 : 'SquareShelfConstrainedStressSSA2dAdolcMumps',
+	3102 : 'SquareShelfConstrainedStressSSA3dAdolcMumps',
+	3103 : 'SquareShelfConstrainedStressHOAdolcMumps',
+	3104 : 'SquareShelfConstrainedStressFSAdolcMumps',
+	3105 : 'SquareShelfConstrainedMasstransp2dAdolcMumps',
+	3106 : 'SquareShelfConstrainedMasstransp2dDGAdolcMumps',
+	3107 : 'SquareShelfConstrainedMasstransp3dAdolcMumps',
+	3108 : 'SquareShelfConstrainedTherSteaAdolcMumps',
+	3109 : 'SquareShelfConstrainedTherTranAdolcMumps',
+	3110 : 'SquareShelfConstrainedTranSSA2dAdolcMumps',
+	3115 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps',
+	3119 : 'SquareShelfConstrainedTherTranAdolcReverseVsForwardMumps',
+	3120 : 'SquareShelfConstrainedTranAdolcReverseVsForwardMumps',
 	}
 
Index: /issm/trunk/test/NightlyRun/android.m
===================================================================
--- /issm/trunk/test/NightlyRun/android.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/android.m	(revision 16560)
@@ -5,5 +5,5 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.verbose=verbose('mprocessor',true,'module',true,'solution',true,'solver',true,'convergence',true,'control',true,'qmu',true,'autodiff',true);
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs={'StressTensor'};
 md=solve(md,StressbalanceSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 16560)
@@ -121,5 +121,5 @@
 	test_ids=intersect(test_ids,[2001:2100]);
 elseif strcmpi(benchmark,'adolc'),
-	test_ids=intersect(test_ids,[3001:3020]);
+	test_ids=intersect(test_ids,[3001:3200]);
 end
 % }}}
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 16560)
@@ -120,5 +120,5 @@
 		test_ids=test_ids.intersection(set(range(2001,2100)))
 	elif strcmpi(benchmark,'adolc'):
-		test_ids=test_ids.intersection(set(range(3001,3020)))
+		test_ids=test_ids.intersection(set(range(3001,3200)))
 	#print 'test_ids after benchmark =',test_ids
 	test_ids=list(test_ids)
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 16560)
@@ -3,13 +3,25 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.cluster=generic('name',oshostname(),'np',2);
+
+%output
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
+md.outputdefinition.definitions={...
+	massfluxatgate('MassFlux1',['../Exp/MassFlux1.exp']),...
+	massfluxatgate('MassFlux2',['../Exp/MassFlux2.exp']),...
+	massfluxatgate('MassFlux3',['../Exp/MassFlux3.exp']),...
+	massfluxatgate('MassFlux4',['../Exp/MassFlux4.exp']),...
+	massfluxatgate('MassFlux5',['../Exp/MassFlux5.exp']),...
+	massfluxatgate('MassFlux6',['../Exp/MassFlux6.exp'])...
+	};
+
 md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vel','Pressure',...
-	'StressTensorxx','StressTensoryy','StressTensorxy'};
+	'StressTensorxx','StressTensoryy','StressTensorxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13};
+	1e-13,1e-13,1e-13,...
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13 };
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
@@ -20,3 +32,9 @@
 	(md.results.StressbalanceSolution.StressTensoryy),...
 	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.MassFlux1),...
+	(md.results.StressbalanceSolution.MassFlux2),...
+	(md.results.StressbalanceSolution.MassFlux3),...
+	(md.results.StressbalanceSolution.MassFlux4),...
+	(md.results.StressbalanceSolution.MassFlux5),...
+	(md.results.StressbalanceSolution.MassFlux6)...
 	};
Index: /issm/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 16560)
@@ -7,4 +7,5 @@
 from solve import *
 from MatlabFuncs import *
+from massfluxatgate import massfluxatgate
 
 md=triangle(model(),'../Exp/Square.exp',50000)
@@ -13,12 +14,24 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.stressbalance.requested_outputs=StressTensorEnum()
+
+#outputs
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
+md.outputdefinition.definitions=[
+		massfluxatgate('MassFlux1','../Exp/MassFlux1.exp'),
+		massfluxatgate('MassFlux2','../Exp/MassFlux2.exp'),
+		massfluxatgate('MassFlux3','../Exp/MassFlux3.exp'),
+		massfluxatgate('MassFlux4','../Exp/MassFlux4.exp'),
+		massfluxatgate('MassFlux5','../Exp/MassFlux5.exp'),
+		massfluxatgate('MassFlux6','../Exp/MassFlux6.exp')
+		]
+
 md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vel','Pressure',\
-	'StressTensorxx','StressTensoryy','StressTensorxy']
+	'StressTensorxx','StressTensoryy','StressTensorxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
-	1e-13,1e-13,1e-13]
+	1e-13,1e-13,1e-13,\
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13 ]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
@@ -29,3 +42,8 @@
 	md.results.StressbalanceSolution.StressTensoryy,\
 	md.results.StressbalanceSolution.StressTensorxy,\
-	]
+	md.results.StressbalanceSolution.MassFlux1,\
+	md.results.StressbalanceSolution.MassFlux2,\
+	md.results.StressbalanceSolution.MassFlux3,\
+	md.results.StressbalanceSolution.MassFlux4,\
+	md.results.StressbalanceSolution.MassFlux5,\
+	md.results.StressbalanceSolution.MassFlux6 ]
Index: /issm/trunk/test/NightlyRun/test103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test103.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test103.m	(revision 16560)
@@ -5,5 +5,5 @@
 md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
 md=solve(md,StressbalanceSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test103.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test103.py	(revision 16560)
@@ -14,5 +14,5 @@
 md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.stressbalance.requested_outputs=StressTensorEnum()
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
 md=solve(md,StressbalanceSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test110.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test110.m	(revision 16560)
@@ -4,5 +4,5 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.requested_outputs=IceVolumeEnum();
+md.transient.requested_outputs={'IceVolume'};
 
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test110.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test110.py	(revision 16560)
@@ -13,5 +13,5 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.requested_outputs=IceVolumeEnum()
+md.transient.requested_outputs=['IceVolume']
 
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test1101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test1101.m	(revision 16560)
@@ -123,5 +123,5 @@
 	1e-10,1e-10,1e-09,...
 	1e-09,1e-09,1e-09,...
-	1e-09,1e-08,1e-09,...
+	1e-09,1e-08,1e-08,...
 	1e-08,1e-08,1e-08,...
 	1e-08,1e-07,1e-08,...
Index: /issm/trunk/test/NightlyRun/test1106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test1106.m	(revision 16560)
@@ -66,6 +66,6 @@
 	1e-12,1e-12,1e-12,...
 	1e-12,2e-12,2e-12,...
-	1e-12,2e-12,2e-12,...
-	1e-12,2e-11,2e-12,...
+	1e-11,2e-12,2e-12,...
+	1e-11,2e-11,2e-12,...
 };
 field_values={};
Index: /issm/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 16560)
@@ -5,5 +5,5 @@
 md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.requested_outputs=IceVolumeEnum();
+md.transient.requested_outputs={'IceVolume'};
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 16560)
@@ -14,5 +14,5 @@
 md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.requested_outputs=IceVolumeEnum()
+md.transient.requested_outputs=['IceVolume']
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk/test/NightlyRun/test120.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test120.m	(revision 16560)
@@ -5,15 +5,18 @@
 md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0;
-md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
 md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
-md=solve(md,EnthalpySolutionEnum());
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Enthalpy','Waterfraction','Temperature'};
-field_tolerances={1e-13,1.45e-10,1e-13};
+field_tolerances={1e-13,2e-10,1e-13};
 field_values={...
-	(md.results.EnthalpySolution.Enthalpy),...
-	(md.results.EnthalpySolution.Waterfraction),...
-	(md.results.EnthalpySolution.Temperature),...
+	(md.results.ThermalSolution.Enthalpy),...
+	(md.results.ThermalSolution.Waterfraction),...
+	(md.results.ThermalSolution.Temperature),...
 	};
Index: /issm/trunk/test/NightlyRun/test120.py
===================================================================
--- /issm/trunk/test/NightlyRun/test120.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test120.py	(revision 16560)
@@ -15,15 +15,18 @@
 md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0
-md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
 md.initialization.watercolumn=numpy.zeros(md.mesh.numberofvertices)
-md=solve(md,EnthalpySolutionEnum())
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,ThermalSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Enthalpy','Waterfraction','Temperature']
-field_tolerances=[1e-13,1.45e-10,1e-13]
+field_tolerances=[1e-13,2e-10,1e-13]
 field_values=[\
-	md.results.EnthalpySolution.Enthalpy,\
-	md.results.EnthalpySolution.Waterfraction,\
-	md.results.EnthalpySolution.Temperature,\
+	md.results.ThermalSolution.Enthalpy,\
+	md.results.ThermalSolution.Waterfraction,\
+	md.results.ThermalSolution.Temperature,\
 	]
Index: /issm/trunk/test/NightlyRun/test1208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test1208.m	(revision 16560)
@@ -31,5 +31,5 @@
 %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_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,2e-07};
 field_values={...
 	(md.results.TransientSolution(end).Vx),...
Index: /issm/trunk/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk/test/NightlyRun/test121.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test121.m	(revision 16560)
@@ -12,4 +12,5 @@
 md.transient.isgroundingline=0;
 md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test121.py
===================================================================
--- /issm/trunk/test/NightlyRun/test121.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test121.py	(revision 16560)
@@ -21,4 +21,5 @@
 md.transient.isgroundingline=False
 md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk/test/NightlyRun/test122.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test122.m	(revision 16560)
@@ -7,4 +7,5 @@
 md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
 md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test122.py
===================================================================
--- /issm/trunk/test/NightlyRun/test122.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test122.py	(revision 16560)
@@ -16,4 +16,5 @@
 md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
 md.thermal.stabilization=2
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test1301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test1301.m	(revision 16560)
@@ -43,4 +43,4 @@
 %Fields and tolerances to track changes
 field_names     ={'BasalMelting'};
-field_tolerances={1e-08};
+field_tolerances={1e-07};
 field_values    ={comp_melting};
Index: /issm/trunk/test/NightlyRun/test1502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test1502.m	(revision 16560)
@@ -5,19 +5,21 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=setflowequation(md,'SSA','all');
-md=extrude(md,3,1.);
-md.cluster=generic('name',oshostname(),'np',2);
+%md=extrude(md,3,1.);
+md.cluster=generic('name',oshostname(),'np',1);
 md.transient.isthermal=0;
 
-md.timestepping.time_step=1.;
-md.settings.output_frequency=1;
-md.timestepping.final_time=2000.;
+%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.surfaceforcings.mass_balance= smb;
+%md.basalforcings.melting_rate= smb;
+md.verbose=verbose('all');
 
 md=solve(md,MasstransportSolutionEnum());
 
+error
 for i=1:10
 	 md=solve(md,MasstransportSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk/test/NightlyRun/test212.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test212.m	(revision 16560)
@@ -10,5 +10,5 @@
 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=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test212.py
===================================================================
--- /issm/trunk/test/NightlyRun/test212.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test212.py	(revision 16560)
@@ -22,5 +22,5 @@
 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=[101]
 md.inversion.cost_functions_coefficients=ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10**7*ones((md.inversion.nsteps,1))
Index: /issm/trunk/test/NightlyRun/test213.m
===================================================================
--- /issm/trunk/test/NightlyRun/test213.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test213.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
@@ -18,5 +18,8 @@
 md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
 
-md.cluster=generic('name',oshostname(),'np',3);
+md.verbose.control=true;
+md.verbose.solution=true;
+
+md.cluster=generic('name',oshostname(),'np',1);
 md=solve(md,StressbalanceSolutionEnum());
 
@@ -27,5 +30,5 @@
 	(md.results.StressbalanceSolution.Gradient1),...
 	md.results.StressbalanceSolution.J,...
-	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
 	(md.results.StressbalanceSolution.Pressure),...
 	(md.results.StressbalanceSolution.Vel),...
Index: /issm/trunk/test/NightlyRun/test213.py
===================================================================
--- /issm/trunk/test/NightlyRun/test213.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test213.py	(revision 16560)
@@ -23,5 +23,5 @@
 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=[101]
 md.inversion.cost_functions_coefficients=ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10**7*ones((md.inversion.nsteps,1))
@@ -44,5 +44,5 @@
 	md.results.StressbalanceSolution.Gradient1,\
 	md.results.StressbalanceSolution.J,\
-	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
 	md.results.StressbalanceSolution.Pressure,\
 	md.results.StressbalanceSolution.Vel,\
Index: /issm/trunk/test/NightlyRun/test214.m
===================================================================
--- /issm/trunk/test/NightlyRun/test214.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test214.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
@@ -27,5 +27,5 @@
 	(md.results.StressbalanceSolution.Gradient1),...
 	(md.results.StressbalanceSolution.J),...
-	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
 	(md.results.StressbalanceSolution.Pressure),...
 	(md.results.StressbalanceSolution.Vel),...
Index: /issm/trunk/test/NightlyRun/test214.py
===================================================================
--- /issm/trunk/test/NightlyRun/test214.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test214.py	(revision 16560)
@@ -23,5 +23,5 @@
 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=[101]
 md.inversion.cost_functions_coefficients=ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10**7*ones((md.inversion.nsteps,1))
@@ -43,5 +43,5 @@
 	md.results.StressbalanceSolution.Gradient1,\
 	md.results.StressbalanceSolution.J,\
-	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
 	md.results.StressbalanceSolution.Pressure,\
 	md.results.StressbalanceSolution.Vel,\
Index: /issm/trunk/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
@@ -23,9 +23,9 @@
 %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_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,3e-09,1e-09};
 field_values={...
 	(md.results.StressbalanceSolution.Gradient1),...
 	(md.results.StressbalanceSolution.J),...
-	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
 	(md.results.StressbalanceSolution.Pressure),...
 	(md.results.StressbalanceSolution.Vel),...
Index: /issm/trunk/test/NightlyRun/test215.py
===================================================================
--- /issm/trunk/test/NightlyRun/test215.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test215.py	(revision 16560)
@@ -23,5 +23,5 @@
 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=[101]
 md.inversion.cost_functions_coefficients=ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10**7*ones((md.inversion.nsteps,1))
@@ -39,9 +39,9 @@
 
 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_tolerances=[1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,3e-09,1e-09]
 field_values=[\
 	md.results.StressbalanceSolution.Gradient1,\
 	md.results.StressbalanceSolution.J,\
-	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
 	md.results.StressbalanceSolution.Pressure,\
 	md.results.StressbalanceSolution.Vel,\
Index: /issm/trunk/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk/test/NightlyRun/test216.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 16560)
@@ -16,5 +16,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={4e-11,2e-11,2e-11,2e-11};
+field_tolerances={4e-11,2e-11,4e-11,2e-11};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test216.py
===================================================================
--- /issm/trunk/test/NightlyRun/test216.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test216.py	(revision 16560)
@@ -29,5 +29,5 @@
 
 field_names     =['Vx','Vy','Vel','Pressure']
-field_tolerances=[2.5e-11,1.5e-11,1e-11,1.5e-11]
+field_tolerances=[4e-11,2e-11,4e-11,2e-11]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 16560)
@@ -57,5 +57,5 @@
 
 md.stressbalance.reltol=10^-5; %tighten for qmu analyses
-md.transient.requested_outputs=IceVolumeEnum();
+md.transient.requested_outputs={'IceVolume'};
 
 %solve
Index: /issm/trunk/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk/test/NightlyRun/test235.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test235.m	(revision 16560)
@@ -52,5 +52,5 @@
 
 md.stressbalance.reltol=10^-5; %tighten for qmu analyses
-md.transient.requested_outputs=IceVolumeEnum();
+md.transient.requested_outputs={'IceVolume'};
 
 %solve
Index: /issm/trunk/test/NightlyRun/test270.m
===================================================================
--- /issm/trunk/test/NightlyRun/test270.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test270.m	(revision 16560)
@@ -2,8 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md.materials=matdamageice();
-md.materials.rheology_B=paterson(md.initialization.temperature);
-md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
-md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test270.py
===================================================================
--- /issm/trunk/test/NightlyRun/test270.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test270.py	(revision 16560)
@@ -4,5 +4,4 @@
 from setmask import *
 from parameterize import *
-from matdamageice import *
 from paterson import *
 from setflowequation import *
@@ -14,8 +13,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md.materials=matdamageice()
-md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
-md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md.damage.D=0.5*numpy.ones((md.mesh.numberofvertices,1))
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test271.m
===================================================================
--- /issm/trunk/test/NightlyRun/test271.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test271.m	(revision 16560)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.law='pralong';
+
+%boundary conditions for damage, to be put in SquareShelf.par
+boundary=zeros(md.mesh.numberofvertices,1);
+boundary(md.mesh.segments(:,1:2))=1;
+pos=find(~md.mask.ice_levelset==0 & boundary==1);
+md.damage.spcdamage(pos)=0;
+
+md.verbose=verbose('solution',true);
+
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DamageEvolutionSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'D'};
+field_tolerances={1e-13};
+field_values={md.results.DamageEvolutionSolution.DamageD};
Index: /issm/trunk/test/NightlyRun/test272.m
===================================================================
--- /issm/trunk/test/NightlyRun/test272.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test272.m	(revision 16560)
@@ -2,17 +2,15 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md.materials=matdamageice();
-md.materials.rheology_B=paterson(md.initialization.temperature);
-md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
-md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
 md=setflowequation(md,'SSA','all');
+md.verbose=verbose('control',true);
 
 %control parameters
 md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyZbar'};
-md.inversion.min_parameters=10^-13*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=ones(md.mesh.numberofvertices,1);
+md.inversion.control_parameters={'DamageDbar'};
+md.inversion.min_parameters=zeros(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=(1-10^-13)*ones(md.mesh.numberofvertices,1);
 md.inversion.nsteps=2;
-md.inversion.cost_functions=101.*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=0.9*ones(md.inversion.nsteps,1);
@@ -26,10 +24,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient','Misfits','MaterialsRheologyZbar','Pressure','Vel','Vx','Vy'};
+field_names     ={'Gradient','Misfits','DamageDbar','Pressure','Vel','Vx','Vy'};
 field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
    (md.results.StressbalanceSolution.Gradient1),...
    (md.results.StressbalanceSolution.J),...
-   (md.results.StressbalanceSolution.MaterialsRheologyZbar),...
+   (md.results.StressbalanceSolution.DamageDbar),...
    (md.results.StressbalanceSolution.Pressure),...
    (md.results.StressbalanceSolution.Vel),...
Index: /issm/trunk/test/NightlyRun/test272.py
===================================================================
--- /issm/trunk/test/NightlyRun/test272.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test272.py	(revision 16560)
@@ -4,5 +4,4 @@
 from setmask import *
 from parameterize import *
-from matdamageice import *
 from paterson import *
 from setflowequation import *
@@ -14,17 +13,14 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md.materials=matdamageice()
-md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
-md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md.damage.D=0.5*numpy.ones((md.mesh.numberofvertices,1))
 md=setflowequation(md,'SSA','all')
 
 #control parameters
 md.inversion.iscontrol=1
-md.inversion.control_parameters=['MaterialsRheologyZbar']
+md.inversion.control_parameters=['DamageDbar']
 md.inversion.min_parameters=10**-13*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.max_parameters=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=101.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions=[101]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=0.9*numpy.ones((md.inversion.nsteps,1))
@@ -38,10 +34,10 @@
 
 #Fields and tolerances to track changes
-field_names     =['Gradient','Misfits','MaterialsRheologyZbar','Pressure','Vel','Vx','Vy']
+field_names     =['Gradient','Misfits','DamageDbar','Pressure','Vel','Vx','Vy']
 field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
 field_values=[\
    md.results.StressbalanceSolution.Gradient1,\
    md.results.StressbalanceSolution.J,\
-   md.results.StressbalanceSolution.MaterialsRheologyZbar,\
+   md.results.StressbalanceSolution.DamageDbar,\
    md.results.StressbalanceSolution.Pressure,\
    md.results.StressbalanceSolution.Vel,\
Index: /issm/trunk/test/NightlyRun/test274.m
===================================================================
--- /issm/trunk/test/NightlyRun/test274.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test274.m	(revision 16560)
@@ -3,8 +3,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf2.par');
-md.materials=matdamageice();
-md.materials.rheology_B=paterson(md.initialization.temperature);
-md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
-md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
 md=setflowequation(md,'SSA','all');
 
Index: /issm/trunk/test/NightlyRun/test274.py
===================================================================
--- /issm/trunk/test/NightlyRun/test274.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test274.py	(revision 16560)
@@ -5,5 +5,4 @@
 from setmask import *
 from parameterize import *
-from matdamageice import *
 from paterson import *
 from setflowequation import *
@@ -16,8 +15,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf2.py')
-md.materials=matdamageice()
-md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
-md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md.damage.D=0.5*numpy.ones((md.mesh.numberofvertices,1))
 md=setflowequation(md,'SSA','all')
 
Index: /issm/trunk/test/NightlyRun/test3001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 16560)
@@ -4,9 +4,8 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.toolkits.DefaultAnalysis=issmsolver();
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorxy'};
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
-md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
 md=solve(md,StressbalanceSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3001.py	(revision 16560)
@@ -13,6 +13,6 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.stressbalance.requested_outputs=StressTensorEnum()
-md.toolkits.DefaultAnalysis=issmsolver()
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorxy']
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,StressbalanceSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 16560)
@@ -6,5 +6,5 @@
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,StressbalanceSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3002.py	(revision 16560)
@@ -15,5 +15,5 @@
 md.cluster=generic('name',oshostname(),'np',1)
 md.autodiff.isautodiff=True
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md=solve(md,StressbalanceSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 16560)
@@ -5,7 +5,7 @@
 md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,StressbalanceSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 16560)
@@ -14,6 +14,6 @@
 md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.stressbalance.requested_outputs=StressTensorEnum()
-md.toolkits.DefaultAnalysis=issmsolver()
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,StressbalanceSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3004.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 16560)
@@ -6,5 +6,5 @@
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,StressbalanceSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3004.py	(revision 16560)
@@ -14,5 +14,5 @@
 md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,StressbalanceSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3005.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 16560)
@@ -5,5 +5,5 @@
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,MasstransportSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3005.py	(revision 16560)
@@ -13,5 +13,5 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,MasstransportSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3006.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 16560)
@@ -8,5 +8,5 @@
 md.masstransport.spcthickness=md.geometry.thickness;
 md.autodiff.isautodiff=true;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,MasstransportSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3006.py	(revision 16560)
@@ -17,5 +17,5 @@
 md.masstransport.stabilization=3
 md.masstransport.spcthickness=md.geometry.thickness
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,MasstransportSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3007.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 16560)
@@ -7,5 +7,5 @@
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md=solve(md,MasstransportSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3007.py	(revision 16560)
@@ -14,5 +14,5 @@
 md.extrude(5,3.)
 md.cluster=generic('name',oshostname(),'np',1)
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,MasstransportSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3008.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 16560)
@@ -8,5 +8,5 @@
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md=solve(md,ThermalSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3008.py	(revision 16560)
@@ -15,5 +15,5 @@
 md.timestepping.time_step=0
 md.cluster=generic('name',oshostname(),'np',1)
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,ThermalSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 16560)
@@ -11,5 +11,5 @@
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3009.py	(revision 16560)
@@ -18,5 +18,5 @@
 md.transient.isthermal=True
 md.transient.isgroundingline=False
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 md.autodiff.isautodiff=True
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 16560)
@@ -4,9 +4,9 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.transient.requested_outputs=IceVolumeEnum();
+md.transient.requested_outputs={'IceVolume'};
 
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3010.py	(revision 16560)
@@ -13,6 +13,6 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.toolkits.DefaultAnalysis=issmsolver()
-md.transient.requested_outputs=IceVolumeEnum()
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.transient.requested_outputs=['IceVolume']
 
 md.autodiff.isautodiff=True
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 16560)
@@ -8,7 +8,7 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.masstransport.requested_outputs=IceVolumeEnum();
+md.masstransport.requested_outputs={'IceVolume'};
 md.verbose=verbose('autodiff',true);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 
 %setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3015.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3015.py	(revision 16560)
@@ -22,6 +22,7 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.masstransport.requested_outputs=IceVolumeEnum()
+md.masstransport.requested_outputs=['IceVolume']
 md.verbose=verbose('autodiff',True)
+md.toolkits.DefaultAnalysis=issmgslsolver()
 
 #setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 16560)
@@ -5,5 +5,5 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 
 md.autodiff.isautodiff=true;
Index: /issm/trunk/test/NightlyRun/test3019.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3019.py	(revision 16560)
@@ -17,4 +17,5 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmgslsolver()
 
 md.autodiff.isautodiff=True
Index: /issm/trunk/test/NightlyRun/test3020.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3020.m	(revision 16560)
@@ -8,8 +8,8 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.transient.requested_outputs=[IceVolumeEnum();MaxVelEnum()];
+md.transient.requested_outputs={'IceVolume','MaxVelEnum'};
 md.verbose=verbose('autodiff',true);
 md.stressbalance.restol=1e-4;
-md.toolkits.DefaultAnalysis=issmsolver();
+md.toolkits.DefaultAnalysis=issmgslsolver();
 
 %setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3020.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3020.py	(revision 16560)
@@ -22,8 +22,8 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.transient.requested_outputs=[IceVolumeEnum(),MaxVelEnum()]
+md.transient.requested_outputs=['IceVolume','MaxVel']
 md.verbose=verbose('autodiff',True)
 md.stressbalance.restol=0.000001
-md.toolkits.DefaultAnalysis=issmsolver()
+md.toolkits.DefaultAnalysis=issmgslsolver()
 
 #setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3021.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3021.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test3021.m	(revision 16560)
@@ -4,8 +4,8 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.stressbalance.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs={'StressTensorxx','StressTensoryy','StressTensorxy'};
 md.autodiff.isautodiff=false;
 md.toolkits.DefaultAnalysis=issmsolver();
-md.verbose=verbose('1111111');
+md.verbose=verbose('all');
 md=solve(md,StressbalanceSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3101.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3101.m	(revision 16560)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorxy'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorxy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	};
Index: /issm/trunk/test/NightlyRun/test3101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3101.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3101.py	(revision 16560)
@@ -0,0 +1,33 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',50000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.requested_outputs=['StressTensor']
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure',\
+	'StressTensorxx','StressTensoryy','StressTensorxy']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
+	1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	]
Index: /issm/trunk/test/NightlyRun/test3102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3102.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3102.m	(revision 16560)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test3102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3102.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3102.py	(revision 16560)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.autodiff.isautodiff=True
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test3103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3103.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3103.m	(revision 16560)
@@ -0,0 +1,30 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
+	};
Index: /issm/trunk/test/NightlyRun/test3103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3103.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3103.py	(revision 16560)
@@ -0,0 +1,38 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure',\
+	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,\
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
+	]
Index: /issm/trunk/test/NightlyRun/test3104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3104.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3104.m	(revision 16560)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test3104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3104.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3104.py	(revision 16560)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2.)
+md=setflowequation(md,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test3105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3105.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3105.m	(revision 16560)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/trunk/test/NightlyRun/test3105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3105.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3105.py	(revision 16560)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/trunk/test/NightlyRun/test3106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3106.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3106.m	(revision 16560)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/trunk/test/NightlyRun/test3106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3106.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3106.py	(revision 16560)
@@ -0,0 +1,28 @@
+from model import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=meshconvert(md)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/trunk/test/NightlyRun/test3107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3107.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3107.m	(revision 16560)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,5,3.);
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/trunk/test/NightlyRun/test3107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3107.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3107.py	(revision 16560)
@@ -0,0 +1,25 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.extrude(5,3.)
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/trunk/test/NightlyRun/test3108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3108.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3108.m	(revision 16560)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,ThermalSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test3108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3108.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3108.py	(revision 16560)
@@ -0,0 +1,27 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.timestepping.time_step=0
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test3109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3109.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3109.m	(revision 16560)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test3109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3109.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3109.py	(revision 16560)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test3110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3110.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3110.m	(revision 16560)
@@ -0,0 +1,43 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs={'IceVolume'};
+
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Volume1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Volume2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Volume3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/trunk/test/NightlyRun/test3110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3110.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3110.py	(revision 16560)
@@ -0,0 +1,51 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.transient.requested_outputs=['IceVolume']
+
+md.autodiff.isautodiff=True
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Volume1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Volume2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Volume3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Bed,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Bed,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].IceVolume,\
+	]
Index: /issm/trunk/test/NightlyRun/test3119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3119.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3119.m	(revision 16560)
@@ -0,0 +1,25 @@
+%test reverse scalar driver in ADOLC, using the test3009 setup, equivalent to test109 setup.
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+md.autodiff.isautodiff=true;
+md.verbose.autodiff=true;
+
+%first run scalar reverse mode: 
+md.autodiff.independents={independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices)};
+md.autodiff.dependents={dependent('name','MaxVel','type','scalar','fos_reverse_index',1)};
+md.autodiff.driver='fos_reverse';
+
+md=solve(md,TransientSolutionEnum());
+
+%recover jacobian: 
+jac_reverse=md.results.TransientSolution(1).AutodiffJacobian;
+
+%Fields and tolerances to track changes
+field_names     ={'Jac Reverse'};
+field_tolerances={1e-8};
+field_values={jac_reverse,};
Index: /issm/trunk/test/NightlyRun/test3119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3119.py	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test3119.py	(revision 16560)
@@ -0,0 +1,37 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from independent import *
+from dependent import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#test reverse scalar vs forward vectorial drivers in ADOLC, using the test3009 setup, equivalent to test109 setup.
+md=triangle(model(),'../Exp/Square.exp',100000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+
+md.autodiff.isautodiff=True
+md.verbose.autodiff=True
+
+#first run scalar reverse mode: 
+md.autodiff.independents=[independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices)]
+md.autodiff.dependents=[dependent('name','MaxVel','type','scalar','fos_reverse_index',1)]
+md.autodiff.driver='fos_reverse'
+
+md=solve(md,TransientSolutionEnum())
+
+#recover jacobian: 
+jac_reverse=md.results.TransientSolution[0].AutodiffJacobian
+
+#Fields and tolerances to track changes
+field_names     =['Jac Reverse']
+field_tolerances=[1e-13]
+field_values=[jac_reverse]
Index: /issm/trunk/test/NightlyRun/test319.m
===================================================================
--- /issm/trunk/test/NightlyRun/test319.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test319.m	(revision 16560)
@@ -10,5 +10,5 @@
 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=[103  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test319.py
===================================================================
--- /issm/trunk/test/NightlyRun/test319.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test319.py	(revision 16560)
@@ -20,5 +20,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[103,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test320.m
===================================================================
--- /issm/trunk/test/NightlyRun/test320.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test320.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[103  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test320.py
===================================================================
--- /issm/trunk/test/NightlyRun/test320.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test320.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[103,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test321.m
===================================================================
--- /issm/trunk/test/NightlyRun/test321.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test321.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[102  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test321.py
===================================================================
--- /issm/trunk/test/NightlyRun/test321.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test321.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((102*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[102,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2*10**-7
Index: /issm/trunk/test/NightlyRun/test322.m
===================================================================
--- /issm/trunk/test/NightlyRun/test322.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[104  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test322.py
===================================================================
--- /issm/trunk/test/NightlyRun/test322.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test322.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((104*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[104,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk/test/NightlyRun/test325.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test325.m	(revision 16560)
@@ -5,8 +5,11 @@
 md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0.;
-md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
 md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
-md=solve(md,EnthalpySolutionEnum());
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,6 +17,6 @@
 field_tolerances={1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.EnthalpySolution.Enthalpy),...
-	(md.results.EnthalpySolution.Waterfraction),...
-	(md.results.EnthalpySolution.Temperature),...
+	(md.results.ThermalSolution.Enthalpy),...
+	(md.results.ThermalSolution.Waterfraction),...
+	(md.results.ThermalSolution.Temperature),...
 	};
Index: /issm/trunk/test/NightlyRun/test325.py
===================================================================
--- /issm/trunk/test/NightlyRun/test325.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test325.py	(revision 16560)
@@ -15,8 +15,11 @@
 md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0.
-md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
 md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
-md=solve(md,EnthalpySolutionEnum())
+md.thermal.isenthalpy = 1
+md.thermal.isdynamicbasalspc = 1
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,ThermalSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -24,6 +27,6 @@
 field_tolerances=[1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.EnthalpySolution.Enthalpy,\
-	md.results.EnthalpySolution.Waterfraction,\
-	md.results.EnthalpySolution.Temperature,\
+	md.results.ThermalSolution.Enthalpy,\
+	md.results.ThermalSolution.Waterfraction,\
+	md.results.ThermalSolution.Temperature,\
 	]
Index: /issm/trunk/test/NightlyRun/test326.m
===================================================================
--- /issm/trunk/test/NightlyRun/test326.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test326.m	(revision 16560)
@@ -12,4 +12,5 @@
 md.transient.isgroundingline=0;
 md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test326.py
===================================================================
--- /issm/trunk/test/NightlyRun/test326.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test326.py	(revision 16560)
@@ -22,4 +22,5 @@
 md.transient.isgroundingline=False
 md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk/test/NightlyRun/test327.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test327.m	(revision 16560)
@@ -10,14 +10,17 @@
 md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272.;
 md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
 md.basalforcings.geothermalflux(:)=5.;
 md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1',...
+field_names     ={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1',...
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2',...
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
-field_tolerances={1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
 	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-4,1e-10};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test327.py
===================================================================
--- /issm/trunk/test/NightlyRun/test327.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test327.py	(revision 16560)
@@ -20,4 +20,5 @@
 md.thermal.spctemperature[numpy.nonzero(md.mesh.vertexonsurface)[0]]=272.
 md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
 md.basalforcings.geothermalflux[:]=5.
 md=solve(md,TransientSolutionEnum())
@@ -29,5 +30,5 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
 	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
-	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-4,1e-10]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk/test/NightlyRun/test328.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test328.m	(revision 16560)
@@ -8,5 +8,5 @@
 md.surfaceforcings.href=md.geometry.surface;
 md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
-md.transient.requested_outputs=TotalSmbEnum();
+md.transient.requested_outputs={'default','TotalSmb'};
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test328.py
===================================================================
--- /issm/trunk/test/NightlyRun/test328.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test328.py	(revision 16560)
@@ -17,5 +17,5 @@
 md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y
 md.surfaceforcings.b_neg=250. + 0.000051*md.mesh.x - 0.00011*md.mesh.y
-md.transient.requested_outputs=TotalSmbEnum()
+md.transient.requested_outputs=['default','TotalSmb']
 md.surfaceforcings.href=copy.deepcopy(md.geometry.surface).reshape(-1)
 md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
Index: /issm/trunk/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk/test/NightlyRun/test329.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test329.m	(revision 16560)
@@ -9,5 +9,5 @@
 md.surfaceforcings.href=md.geometry.surface;
 md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
-md.transient.requested_outputs=TotalSmbEnum();
+md.transient.requested_outputs={'default','TotalSmb'};
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test329.py
===================================================================
--- /issm/trunk/test/NightlyRun/test329.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test329.py	(revision 16560)
@@ -20,5 +20,5 @@
 md.surfaceforcings.href=copy.deepcopy(md.geometry.surface).reshape(-1)
 md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
-md.transient.requested_outputs=TotalSmbEnum()
+md.transient.requested_outputs=['default','TotalSmb']
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test331.m
===================================================================
--- /issm/trunk/test/NightlyRun/test331.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test331.m	(revision 16560)
@@ -6,5 +6,5 @@
 md.initialization.watercolumn=10^-3*ones(md.mesh.numberofvertices,1);
 md.hydrology.spcwatercolumn=NaN*ones(md.mesh.numberofvertices,1);
-pos=find(md.mesh.y==0);
+pos=find(md.mesh.y==0 | md.mesh.x==0);
 md.hydrology.spcwatercolumn(pos)=2*10^-3;
 md=solve(md,HydrologySolutionEnum());
Index: /issm/trunk/test/NightlyRun/test331.py
===================================================================
--- /issm/trunk/test/NightlyRun/test331.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test331.py	(revision 16560)
@@ -17,5 +17,5 @@
 md.initialization.watercolumn=1e-3*numpy.ones((md.mesh.numberofvertices,1))
 md.hydrology.spcwatercolumn=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-pos=numpy.nonzero(md.mesh.y==0)[0]
+pos=numpy.nonzero(numpy.logical_or(md.mesh.y==0.,md.mesh.x==0.))[0]
 md.hydrology.spcwatercolumn[pos]=2e-3
 md=solve(md,HydrologySolutionEnum())
Index: /issm/trunk/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk/test/NightlyRun/test332.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test332.m	(revision 16560)
@@ -16,5 +16,4 @@
 md.timestepping.time_step=0;
 md.timestepping.final_time=1.0;
-%md.verbose=verbose('1111111');
 md=solve(md,HydrologySolutionEnum());
 
@@ -25,3 +24,3 @@
 field_names     ={'SedimentWaterHead','SedimentHeadResidual'};
 field_tolerances={1e-13, 2.5e-10};
-field_values={md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual}
+field_values={md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual};
Index: /issm/trunk/test/NightlyRun/test411.py
===================================================================
--- /issm/trunk/test/NightlyRun/test411.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test411.py	(revision 16560)
@@ -15,5 +15,5 @@
 md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.timestepping.time_step=0
+md.timestepping.time_step=0.
 md=solve(md,SteadystateSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[103  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test415.py
===================================================================
--- /issm/trunk/test/NightlyRun/test415.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test415.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[103,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test416.m
===================================================================
--- /issm/trunk/test/NightlyRun/test416.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test416.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[102  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test416.py
===================================================================
--- /issm/trunk/test/NightlyRun/test416.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test416.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((102*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[102,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test421.py
===================================================================
--- /issm/trunk/test/NightlyRun/test421.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test421.py	(revision 16560)
@@ -19,5 +19,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-07,1e-07,2e-05,1e-07,2e-07]
+field_tolerances=[2e-07,1e-07,2e-05,1e-07,2e-07]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test422.m
===================================================================
--- /issm/trunk/test/NightlyRun/test422.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test422.m	(revision 16560)
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,2e-07,2e-06,2e-07,5e-07};
+field_tolerances={2e-07,2e-07,2e-06,2e-07,5e-07};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test422.py
===================================================================
--- /issm/trunk/test/NightlyRun/test422.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test422.py	(revision 16560)
@@ -20,5 +20,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-07,2e-07,1e-06,2e-07,1e-07]
+field_tolerances=[2e-07,2e-07,2e-06,2e-07,5e-07]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk/test/NightlyRun/test424.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 16560)
@@ -13,4 +13,5 @@
 md.transient.isgroundingline=1;
 md.groundingline.migration='AgressiveMigration';
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
 
 md.cluster=generic('name',oshostname(),'np',3);
@@ -18,10 +19,10 @@
 
 %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_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Bed),...
@@ -29,11 +30,17 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).IceVolume),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
 	};
Index: /issm/trunk/test/NightlyRun/test424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test424.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test424.py	(revision 16560)
@@ -23,4 +23,5 @@
 md.transient.isgroundingline=True
 md.groundingline.migration='AgressiveMigration'
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
 
 md.cluster=generic('name',oshostname(),'np',3)
@@ -28,10 +29,10 @@
 
 #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_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',\
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',\
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Bed,\
@@ -39,11 +40,17 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeAboveFloatation,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].IceVolume,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation,\
 	]
Index: /issm/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 16560)
@@ -14,4 +14,5 @@
 md.transient.isgroundingline=1;
 md.groundingline.migration='AgressiveMigration';
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -19,10 +20,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
-	'Bed2','Surface2','Thickness2','Floatingice2',...
-	'Bed3','Surface3','Thickness3','Floatingice3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-11,1e-10,1e-11,1.25e-11,...
-	1e-10,1e-10,1e-10,1.15e-11};
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-11,1e-10,1e-11,1.25e-11,1e-13,1e-13,...
+	1e-10,1e-10,1e-10,1.15e-11,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Bed),...
@@ -30,11 +31,17 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).IceVolume),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
 	};
Index: /issm/trunk/test/NightlyRun/test426.py
===================================================================
--- /issm/trunk/test/NightlyRun/test426.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test426.py	(revision 16560)
@@ -24,4 +24,5 @@
 md.transient.isgroundingline=True
 md.groundingline.migration='AgressiveMigration'
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
 md.cluster=generic('name',oshostname(),'np',3)
 
@@ -29,11 +30,11 @@
 
 #Fields and tolerances to track changes
-field_names     =['Bed1','Surface1','Thickness1','Floatingice1',\
-	'Bed2','Surface2','Thickness2','Floatingice2',\
-	'Bed3','Surface3','Thickness3','Floatingice3']
+field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',\
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',\
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3',]
 
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
-	1e-11,1e-10,1e-11,1.25e-11,\
-	1e-10,1e-10,1e-10,1.15e-11]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+	1e-11,1e-10,1e-11,1.25e-11,1e-13,1e-13,\
+	1e-10,1e-10,1e-10,1.15e-11,1e-13,1e-13]
 
 field_values=[\
@@ -42,11 +43,17 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeAboveFloatation,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].IceVolume,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation,\
 	]
Index: /issm/trunk/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk/test/NightlyRun/test431.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test431.m	(revision 16560)
@@ -7,4 +7,5 @@
 md.timestepping.time_step=0.;
 md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
 md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/NightlyRun/test431.py
===================================================================
--- /issm/trunk/test/NightlyRun/test431.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test431.py	(revision 16560)
@@ -17,4 +17,5 @@
 md.timestepping.time_step=0.
 md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
 md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
Index: /issm/trunk/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk/test/NightlyRun/test511.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test511.m	(revision 16560)
@@ -16,5 +16,5 @@
 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=101;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10.^8*ones(md.inversion.nsteps,1);
@@ -32,5 +32,5 @@
 	(md.results.StressbalanceSolution.Gradient1),...
 	(md.results.StressbalanceSolution.J),...
-	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
 	(md.results.StressbalanceSolution.Pressure),...
 	(md.results.StressbalanceSolution.Vel),...
Index: /issm/trunk/test/NightlyRun/test511.py
===================================================================
--- /issm/trunk/test/NightlyRun/test511.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test511.py	(revision 16560)
@@ -26,5 +26,5 @@
 md.inversion.max_parameters=2.*10**9*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=101*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions=[101]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10.**8*numpy.ones((md.inversion.nsteps,1))
@@ -43,5 +43,5 @@
 	md.results.StressbalanceSolution.Gradient1,\
 	md.results.StressbalanceSolution.J,\
-	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
 	md.results.StressbalanceSolution.Pressure,\
 	md.results.StressbalanceSolution.Vel,\
Index: /issm/trunk/test/NightlyRun/test512.m
===================================================================
--- /issm/trunk/test/NightlyRun/test512.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test512.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[103  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test512.py
===================================================================
--- /issm/trunk/test/NightlyRun/test512.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test512.py	(revision 16560)
@@ -21,5 +21,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[103,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test513.m
===================================================================
--- /issm/trunk/test/NightlyRun/test513.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test513.m	(revision 16560)
@@ -11,5 +11,5 @@
 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=[103  501];
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
 md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test513.py
===================================================================
--- /issm/trunk/test/NightlyRun/test513.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test513.py	(revision 16560)
@@ -20,5 +20,5 @@
 md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.nsteps=2
-md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions=[103,501]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
 md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
Index: /issm/trunk/test/NightlyRun/test611.m
===================================================================
--- /issm/trunk/test/NightlyRun/test611.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test611.m	(revision 16560)
@@ -12,5 +12,5 @@
 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=201;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10./md.constants.yts*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test611.py
===================================================================
--- /issm/trunk/test/NightlyRun/test611.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test611.py	(revision 16560)
@@ -22,5 +22,5 @@
 md.inversion.min_parameters=-50.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.max_parameters=50.*numpy.ones((md.mesh.numberofvertices,1))
-md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions=[201]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10./md.constants.yts*numpy.ones((md.inversion.nsteps,1))
Index: /issm/trunk/test/NightlyRun/test612.m
===================================================================
--- /issm/trunk/test/NightlyRun/test612.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test612.m	(revision 16560)
@@ -13,5 +13,5 @@
 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=201;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.gradient_scaling=10./md.constants.yts*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test612.py
===================================================================
--- /issm/trunk/test/NightlyRun/test612.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test612.py	(revision 16560)
@@ -24,5 +24,5 @@
 md.inversion.min_parameters=-50.*numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.max_parameters=50.*numpy.ones((md.mesh.numberofvertices,1))
-md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions=[201]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.gradient_scaling=10./md.constants.yts*numpy.ones((md.inversion.nsteps,1))
Index: /issm/trunk/test/NightlyRun/test613.m
===================================================================
--- /issm/trunk/test/NightlyRun/test613.m	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test613.m	(revision 16560)
@@ -19,5 +19,5 @@
 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=201;
 md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
 md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
Index: /issm/trunk/test/NightlyRun/test613.py
===================================================================
--- /issm/trunk/test/NightlyRun/test613.py	(revision 16559)
+++ /issm/trunk/test/NightlyRun/test613.py	(revision 16560)
@@ -31,5 +31,5 @@
 md.inversion.min_parameters=numpy.hstack((-2000.*numpy.ones((md.mesh.numberofvertices,1)),-2000.*numpy.ones((md.mesh.numberofvertices,1))))
 md.inversion.max_parameters=numpy.hstack((+2000.*numpy.ones((md.mesh.numberofvertices,1)),+2000.*numpy.ones((md.mesh.numberofvertices,1))))
-md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions=[201]
 md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
 md.inversion.maxiter_per_step=4*numpy.ones((md.inversion.nsteps,1))
Index: /issm/trunk/test/NightlyRun/test701.m
===================================================================
--- /issm/trunk/test/NightlyRun/test701.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test701.m	(revision 16560)
@@ -0,0 +1,58 @@
+x =[1:100:3000]';
+h=linspace(1000,300,numel(x))';
+b=-917/1023*h;
+
+md=bamgflowband(model(),x,b+h,b,'hmax',80);
+
+%Geometry
+md.geometry.surface   = interp1(x,b+h,md.mesh.x);
+md.geometry.bed       = interp1(x,b,md.mesh.x);
+md.geometry.thickness = md.geometry.surface-md.geometry.bed;
+
+%mask
+md.mask.ice_levelset  = ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(vertexflags(md.mesh,2))) = 0;
+md.mask.groundedice_levelset = double(md.mesh.x<0)-.5;
+
+%materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN(md.mesh.numberofvertices,1);
+
+%friction
+md.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(vertexflags(md.mesh,1)))=20;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Boundary conditions
+md.stressbalance.referential  = NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce = 0*ones(md.mesh.numberofvertices,3);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=0;
+md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
+%md.stressbalance.spcvx(find(vertexflags(md.mesh,4) | vertexflags(md.mesh,2)))=0;
+%md.stressbalance.spcvy(find(vertexflags(md.mesh,4) | vertexflags(md.mesh,2)))=0;
+
+%Misc
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.stressbalance.abstol=NaN;
+md.miscellaneous.name = 'flowline';
+
+%Go solve
+md.cluster=generic('np',2);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure)};
Index: /issm/trunk/test/NightlyRun/test702.m
===================================================================
--- /issm/trunk/test/NightlyRun/test702.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/test702.m	(revision 16560)
@@ -0,0 +1,53 @@
+%mesh parameters
+x =[-5:.5:5]';
+[b h sea]=NowickiProfile(x);
+x = x*10^3;
+h = h*10^3;
+b = (b-sea)*10^3;
+
+%mesh domain
+md=bamgflowband(model(),x,b+h,b,'hmax',150);
+
+%parameterize
+md.geometry.surface   = interp1(x,b+h,md.mesh.x);
+md.geometry.bed       = interp1(x,b,md.mesh.x);
+md.geometry.thickness = md.geometry.surface-md.geometry.bed;
+md.mask.ice_levelset = ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(vertexflags(md.mesh,2))) = 0;
+md.mask.groundedice_levelset = double(md.mesh.x<0)-.5;
+
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN(md.mesh.numberofvertices,1);
+md.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(vertexflags(md.mesh,1)))=20;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=800;
+md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
+
+%Misc
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.stressbalance.abstol=NaN;
+md.miscellaneous.name = 'flowline';
+
+%Go solve
+md.cluster=generic('np',2);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure)};
Index: /issm/trunk/test/NightlyRun/testad.m
===================================================================
--- /issm/trunk/test/NightlyRun/testad.m	(revision 16560)
+++ /issm/trunk/test/NightlyRun/testad.m	(revision 16560)
@@ -0,0 +1,28 @@
+%test reverse scalar vs forward vectorial drivers in ADOLC, using the test3009 setup, equivalent to test109 setup.
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+%md.debug.valgrind=true;
+%md.verbose=verbose('11111111')
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+%md.toolkits.DefaultAnalysis.solver_type='gsl';
+
+md.autodiff.isautodiff=true;
+md.verbose.autodiff=true;
+
+%first run scalar reverse mode: 
+md.autodiff.independents={independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices)};
+md.autodiff.dependents={dependent('name','MaxVel','type','scalar','fos_reverse_index',1)};
+md.autodiff.driver='fos_reverse';
+
+md=solve(md,TransientSolutionEnum());
+
+%recover jacobian: 
+jac_reverse=md.results.TransientSolution(1).AutodiffJacobian;
+
+%Fields and tolerances to track changes
+field_names     ={'Jac Reverse'};
+field_tolerances={1e-8};
+field_values={jac_reverse};
Index: sm/trunk/test/NightlyRun/tmp332.m
===================================================================
--- /issm/trunk/test/NightlyRun/tmp332.m	(revision 16559)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model(),'../Exp/Square.exp',50000.);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',2);
-md.hydrology=(hydrologydc);
-md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
-md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
-pos=find(md.mesh.x==0);
-md.hydrology.spcsediment_head(pos)=0.0;
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
-md.timestepping.time_step=0;
-md.timestepping.final_time=1.0;
-md=solve(md,HydrologySolutionEnum());
-
-analitic=(md.mesh.x.^2-2*md.mesh.x*10^6)*(-2.0/(365*3600*24*2.0*md.hydrology.sediment_transmitivity));
-plotmodel(md,'data',md.results.HydrologySolution.SedimentHead-analitic)
-%plotmodel(md,'data',analitic)
Index: /issm/trunk/test/Par/79North.par
===================================================================
--- /issm/trunk/test/Par/79North.par	(revision 16559)
+++ /issm/trunk/test/Par/79North.par	(revision 16560)
@@ -20,4 +20,7 @@
 md.materials.rheology_B=paterson(md.initialization.temperature);
 md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
 
 %Friction
Index: /issm/trunk/test/Par/79North.py
===================================================================
--- /issm/trunk/test/Par/79North.py	(revision 16559)
+++ /issm/trunk/test/Par/79North.py	(revision 16560)
@@ -2,9 +2,9 @@
 import inspect
 import netCDF4
-from numpy import *
-from verbose import *
+import numpy
+from verbose import verbose 
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetMarineIceSheetBC import *
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Start defining model parameters here
@@ -12,6 +12,6 @@
 #Geometry and observation
 f         = netCDF4.Dataset('../Data/79North.nc','r')
-x         = reshape(f.variables['x'][:],(-1))
-y         = reshape(f.variables['y'][:],(-1))
+x         = numpy.reshape(f.variables['x'][:],(-1))
+y         = numpy.reshape(f.variables['y'][:],(-1))
 vx        = f.variables['vx'][:]
 vy        = f.variables['vy'][:]
@@ -28,17 +28,20 @@
 
 #Materials
-md.initialization.temperature=(273.-20.)*ones((md.mesh.numberofvertices,1))
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
 md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*ones((md.mesh.numberofelements,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 md.initialization.temperature=md.initialization.temperature
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 #Friction
-md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient=50.*numpy.ones((md.mesh.numberofvertices,1))
 md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
-md.friction.p=ones((md.mesh.numberofelements,1))
-md.friction.q=ones((md.mesh.numberofelements,1))
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Ice shelf melting and surface mass balance 
-md.basalforcings.melting_rate=zeros((md.mesh.numberofvertices,1))
+md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
 md.basalforcings.melting_rate[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.surfaceforcings.mass_balance=15*numpy.ones((md.mesh.numberofvertices,1))
Index: /issm/trunk/test/Par/GiaBenchmarksAB.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 16559)
+++ /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 16560)
@@ -44,4 +44,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Friction
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/GiaBenchmarksCD.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 16559)
+++ /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 16560)
@@ -43,4 +43,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Friction
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/ISMIPA.par
===================================================================
--- /issm/trunk/test/Par/ISMIPA.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPA.par	(revision 16560)
@@ -16,4 +16,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      boundary conditions for stressbalance model');
 %Create node on boundary first (because we cannot use mesh)
Index: /issm/trunk/test/Par/ISMIPA.py
===================================================================
--- /issm/trunk/test/Par/ISMIPA.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPA.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -19,4 +19,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      boundary conditions for stressbalance model"
 #Create node on boundary first (because we cannot use mesh)
Index: /issm/trunk/test/Par/ISMIPB.par
===================================================================
--- /issm/trunk/test/Par/ISMIPB.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPB.par	(revision 16560)
@@ -16,4 +16,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      boundary conditions for stressbalance model');
 %Create node on boundary first (because we cannot use mesh)
Index: /issm/trunk/test/Par/ISMIPB.py
===================================================================
--- /issm/trunk/test/Par/ISMIPB.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPB.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -19,4 +19,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      boundary conditions for stressbalance model"
 #Create node on boundary first (because we cannot use mesh)
Index: /issm/trunk/test/Par/ISMIPC.par
===================================================================
--- /issm/trunk/test/Par/ISMIPC.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPC.par	(revision 16560)
@@ -17,4 +17,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPC.py
===================================================================
--- /issm/trunk/test/Par/ISMIPC.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPC.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -20,4 +20,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPD.par
===================================================================
--- /issm/trunk/test/Par/ISMIPD.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPD.par	(revision 16560)
@@ -16,4 +16,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPD.py
===================================================================
--- /issm/trunk/test/Par/ISMIPD.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPD.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -19,4 +19,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPE.par
===================================================================
--- /issm/trunk/test/Par/ISMIPE.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPE.par	(revision 16560)
@@ -26,4 +26,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPE.py
===================================================================
--- /issm/trunk/test/Par/ISMIPE.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPE.py	(revision 16560)
@@ -1,5 +1,5 @@
 import numpy
 import netCDF4
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -31,4 +31,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
Index: /issm/trunk/test/Par/ISMIPF.par
===================================================================
--- /issm/trunk/test/Par/ISMIPF.par	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPF.par	(revision 16560)
@@ -17,4 +17,7 @@
 md.materials.rheology_n=1.*ones(md.mesh.numberofelements,1);
 md.materials.rheology_law='None';
+
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
 
 disp('      boundary conditions for stressbalance model');
Index: /issm/trunk/test/Par/ISMIPF.py
===================================================================
--- /issm/trunk/test/Par/ISMIPF.py	(revision 16559)
+++ /issm/trunk/test/Par/ISMIPF.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetIceSheetBC import *
+from SetIceSheetBC import SetIceSheetBC
 
 #Ok, start defining model parameters here
@@ -20,4 +20,7 @@
 md.materials.rheology_n=1.*numpy.ones((md.mesh.numberofelements,1))
 md.materials.rheology_law='None'
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 print "      boundary conditions for stressbalance model"
Index: /issm/trunk/test/Par/Pig.par
===================================================================
--- /issm/trunk/test/Par/Pig.par	(revision 16559)
+++ /issm/trunk/test/Par/Pig.par	(revision 16560)
@@ -26,4 +26,7 @@
 md.initialization.temperature=md.initialization.temperature;
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Friction
 md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/Pig.py
===================================================================
--- /issm/trunk/test/Par/Pig.py	(revision 16559)
+++ /issm/trunk/test/Par/Pig.py	(revision 16560)
@@ -2,9 +2,9 @@
 import inspect
 import netCDF4
-from numpy import *
-from verbose import *
+import numpy
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetMarineIceSheetBC import *
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Start defining model parameters here
@@ -12,6 +12,6 @@
 #Geometry and observation
 f = netCDF4.Dataset('../Data/Pig.nc','r')
-x         = reshape(f.variables['x'][:],(-1))
-y         = reshape(f.variables['y'][:],(-1))
+x         = numpy.reshape(f.variables['x'][:],(-1))
+y         = numpy.reshape(f.variables['y'][:],(-1))
 vx_obs    = f.variables['vx_obs'][:]
 vy_obs    = f.variables['vy_obs'][:]
@@ -28,18 +28,21 @@
 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))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Materials
-md.initialization.temperature=(273.-20.)*ones((md.mesh.numberofvertices,1))
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
 md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*ones((md.mesh.numberofelements,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 md.initialization.temperature=md.initialization.temperature
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 #Friction
-md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient=50.*numpy.ones((md.mesh.numberofvertices,1))
 md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
-md.friction.p=ones((md.mesh.numberofelements,1))
-md.friction.q=ones((md.mesh.numberofelements,1))
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
Index: /issm/trunk/test/Par/RoundSheetEISMINT.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetEISMINT.par	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetEISMINT.par	(revision 16560)
@@ -20,4 +20,7 @@
 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);
+
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
 
 disp('      creating surface mass balance');
Index: /issm/trunk/test/Par/RoundSheetEISMINT.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetEISMINT.py	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetEISMINT.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetMarineIceSheetBC import *
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Ok, start defining model parameters here
@@ -23,4 +23,7 @@
 md.materials.rheology_B=6.81*10**7*numpy.ones((md.mesh.numberofvertices,1))    #to have the same B as the analytical solution 
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 print "      creating surface mass balance"
Index: /issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.par	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetShelf.par	(revision 16560)
@@ -61,4 +61,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=-10.*ones(md.mesh.numberofvertices,1);
@@ -109,4 +112,5 @@
 md.mask.ice_levelset(find(md.mesh.vertexonboundary))=0;
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
 md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
Index: /issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.py	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetShelf.py	(revision 16560)
@@ -3,6 +3,6 @@
 import copy
 import inspect
-from paterson import *
-from verbose import *
+from paterson import paterson
+from verbose import verbose
 
 #Start defining model parameters here
@@ -68,4 +68,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 #Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=-10.*numpy.ones((md.mesh.numberofvertices,1))
@@ -119,4 +122,5 @@
 md.mask.ice_levelset[pos]=0
 md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
Index: /issm/trunk/test/Par/RoundSheetStaticEISMINT.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetStaticEISMINT.par	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetStaticEISMINT.par	(revision 16560)
@@ -24,4 +24,7 @@
 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);
+
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
 
 disp('      creating surface mass balance');
Index: /issm/trunk/test/Par/RoundSheetStaticEISMINT.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetStaticEISMINT.py	(revision 16559)
+++ /issm/trunk/test/Par/RoundSheetStaticEISMINT.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetMarineIceSheetBC import *
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 print "      creating thickness"
@@ -27,4 +27,7 @@
 md.materials.rheology_B=6.81*10**7*numpy.ones((md.mesh.numberofvertices,1))    #to have the same B as the analytical solution 
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 print "      creating surface mass balance"
Index: /issm/trunk/test/Par/SquareEISMINT.par
===================================================================
--- /issm/trunk/test/Par/SquareEISMINT.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareEISMINT.par	(revision 16560)
@@ -26,4 +26,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      creating surface mass balance');
 md.surfaceforcings.mass_balance=0.2*ones(md.mesh.numberofvertices,1); %0m/a
Index: /issm/trunk/test/Par/SquareEISMINT.py
===================================================================
--- /issm/trunk/test/Par/SquareEISMINT.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareEISMINT.py	(revision 16560)
@@ -1,4 +1,4 @@
 import numpy
-from SetMarineIceSheetBC import *
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Ok, start defining model parameters here
@@ -29,4 +29,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      creating surface mass balance"
 md.surfaceforcings.mass_balance=0.2*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 16560)
@@ -29,4 +29,7 @@
 md.materials.rheology_B=paterson(md.initialization.temperature);
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
 
 %Friction
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 16560)
@@ -3,8 +3,8 @@
 import numpy
 import inspect
-from verbose import *
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetIceSheetBC import *
+from paterson import paterson
+from SetIceSheetBC import SetIceSheetBC
 
 #Start defining model parameters here
@@ -39,4 +39,7 @@
 md.materials.rheology_B=paterson(md.initialization.temperature)
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Friction
@@ -73,3 +76,2 @@
 if len(inspect.stack()) > 2:
 	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
-
Index: /issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareSheetShelf.par	(revision 16560)
@@ -32,4 +32,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Accumulation and melting
 md.surfaceforcings.mass_balance=10.*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/SquareSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareSheetShelf.py	(revision 16560)
@@ -2,9 +2,9 @@
 import inspect
 import netCDF4
-from numpy import *
-from verbose import *
+import numpy
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetMarineIceSheetBC import *
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Start defining model parameters here
@@ -26,6 +26,6 @@
 #Initial velocity 
 f = netCDF4.Dataset('../Data/SquareSheetShelf.nc','r')
-x         = reshape(f.variables['x'][:],(-1))
-y         = reshape(f.variables['y'][:],(-1))
+x         = numpy.reshape(f.variables['x'][:],(-1))
+y         = numpy.reshape(f.variables['y'][:],(-1))
 vx        = f.variables['vx'][:]
 vy        = f.variables['vy'][:]
@@ -35,11 +35,14 @@
 [md.initialization.vx]  = InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
 [md.initialization.vy]  = InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
-md.initialization.vz=zeros((md.mesh.numberofvertices,1))
-md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Materials
-md.initialization.temperature=(273.-20.)*ones((md.mesh.numberofvertices,1))
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
 md.materials.rheology_B=paterson(md.initialization.temperature)
-md.materials.rheology_n=3.*ones((md.mesh.numberofelements,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Accumulation and melting
@@ -48,8 +51,8 @@
 
 #Friction
-md.friction.coefficient=20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
 md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
-md.friction.p=ones((md.mesh.numberofelements,1))
-md.friction.q=ones((md.mesh.numberofelements,1))
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
Index: /issm/trunk/test/Par/SquareShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelf.par	(revision 16560)
@@ -29,4 +29,7 @@
 md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Friction
 md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/SquareShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelf.py	(revision 16560)
@@ -2,9 +2,9 @@
 import inspect
 import netCDF4
-from numpy import *
-from verbose import *
+import numpy
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetIceShelfBC import *
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
 
 #Start defining model parameters here
@@ -23,6 +23,6 @@
 iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
 
-x=reshape(iVelF.variables['x'][:],(-1))
-y=reshape(iVelF.variables['y'][:],(-1))
+x=numpy.reshape(iVelF.variables['x'][:],(-1))
+y=numpy.reshape(iVelF.variables['y'][:],(-1))
 vx=iVelF.variables['vx'][:]
 vy=iVelF.variables['vy'][:]
@@ -39,6 +39,6 @@
 [md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
 [md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
-md.initialization.vz=zeros((md.mesh.numberofvertices,1))
-md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
 
 #dbg - begin
@@ -55,13 +55,16 @@
 
 #Materials
-md.initialization.temperature = (273.-20.)*ones((md.mesh.numberofvertices,1))
+md.initialization.temperature = (273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
 md.materials.rheology_B = paterson(md.initialization.temperature)
-md.materials.rheology_n = 3.*ones((md.mesh.numberofelements,1))
+md.materials.rheology_n = 3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Friction
-md.friction.coefficient = 20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient = 20.*numpy.ones((md.mesh.numberofvertices,1))
 md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
-md.friction.p = ones((md.mesh.numberofelements,1))
-md.friction.q = ones((md.mesh.numberofelements,1))
+md.friction.p = numpy.ones((md.mesh.numberofelements,1))
+md.friction.q = numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
@@ -74,5 +77,5 @@
 md.steadystate.reltol = 0.02
 md.stressbalance.reltol = 0.02
-md.stressbalance.abstol = nan
+md.stressbalance.abstol = float('nan')
 md.timestepping.time_step = 1.
 md.timestepping.final_time = 3.
Index: /issm/trunk/test/Par/SquareShelf2.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelf2.par	(revision 16560)
@@ -29,4 +29,7 @@
 md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Friction
 md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/SquareShelf2.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelf2.py	(revision 16560)
@@ -2,9 +2,9 @@
 import inspect
 import netCDF4
-from numpy import *
-from verbose import *
+import numpy
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetIceShelfBC import *
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
 
 #Start defining model parameters here
@@ -23,6 +23,6 @@
 iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
 
-x=reshape(iVelF.variables['x'][:],(-1))
-y=reshape(iVelF.variables['y'][:],(-1))
+x=numpy.reshape(iVelF.variables['x'][:],(-1))
+y=numpy.reshape(iVelF.variables['y'][:],(-1))
 vx=iVelF.variables['vx'][:]
 vy=iVelF.variables['vy'][:]
@@ -39,6 +39,6 @@
 [md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
 [md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
-md.initialization.vz=zeros((md.mesh.numberofvertices,1))
-md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
 
 #dbg - begin
@@ -55,13 +55,16 @@
 
 #Materials
-md.initialization.temperature = (273.-20.)*ones((md.mesh.numberofvertices,1))
+md.initialization.temperature = (273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
 md.materials.rheology_B = paterson(md.initialization.temperature)
-md.materials.rheology_n = 3.*ones((md.mesh.numberofelements,1))
+md.materials.rheology_n = 3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
 
 #Friction
-md.friction.coefficient = 20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient = 20.*numpy.ones((md.mesh.numberofvertices,1))
 md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
-md.friction.p = ones((md.mesh.numberofelements,1))
-md.friction.q = ones((md.mesh.numberofelements,1))
+md.friction.p = numpy.ones((md.mesh.numberofelements,1))
+md.friction.q = numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
@@ -74,5 +77,5 @@
 md.steadystate.reltol = 0.02
 md.stressbalance.reltol = 0.02
-md.stressbalance.abstol = nan
+md.stressbalance.abstol = float('nan')
 md.timestepping.time_step = 1.
 md.timestepping.final_time = 3.
Index: /issm/trunk/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 16560)
@@ -29,4 +29,7 @@
 md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 %Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=10*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 16560)
@@ -3,8 +3,8 @@
 import numpy
 import inspect
-from verbose import *
+from verbose import verbose
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
-from paterson import *
-from SetIceShelfBC import *
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
 
 #Start defining model parameters here
@@ -40,4 +40,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 #Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
@@ -69,3 +72,2 @@
 if len(inspect.stack()) > 2:
 	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
-
Index: /issm/trunk/test/Par/SquareThermal.par
===================================================================
--- /issm/trunk/test/Par/SquareThermal.par	(revision 16559)
+++ /issm/trunk/test/Par/SquareThermal.par	(revision 16560)
@@ -27,4 +27,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
+%Damage
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
 disp('      creating surface mass balance');
 md.surfaceforcings.mass_balance=ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
@@ -39,3 +42,3 @@
 md.thermal.spctemperature(:)=md.initialization.temperature;
 md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1); 
-md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.)=1.*10^-3; %1 mW/m^2
+md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.))=1.*10^-3; %1 mW/m^2
Index: /issm/trunk/test/Par/SquareThermal.py
===================================================================
--- /issm/trunk/test/Par/SquareThermal.py	(revision 16559)
+++ /issm/trunk/test/Par/SquareThermal.py	(revision 16560)
@@ -1,5 +1,5 @@
 import numpy
-from paterson import *
-from SetMarineIceSheetBC import *
+from paterson import paterson
+from SetMarineIceSheetBC import SetMarineIceSheetBC
 
 #Ok, start defining model parameters here
@@ -31,4 +31,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
+#Damage
+md.damage.D=numpy.zeros((md.mesh.numberofvertices,1))
+
 print "      creating surface mass balance"
 md.surfaceforcings.mass_balance=numpy.ones((md.mesh.numberofvertices,1))/md.constants.yts    #1m/a
