Index: /issm/branches/trunk-jpl-damage/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/Makefile.am	(revision 13101)
@@ -1,3 +1,5 @@
 EXTRA_DIST = reconf scripts test m4 examples cron etc doc packages contributors.txt 
-SUBDIRS = src bin
+SUBDIRS = src
 bin_SCRIPTS=config.h startup.m README.rtf
+
+ACLOCAL_AMFLAGS = -I externalpackages/libtool/install/share/aclocal
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh	(revision 13101)
@@ -3,18 +3,6 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--without-modules\
-	--without-thermal \
-	--without-control \
-	--without-hydrology \
-	--without-diagnostic \
-	--without-balanced \
-	--without-responses \
-	--without-slope \
-	--without-rifts \
-	--without-steadystate \
-	--without-transient \
-	--without-3d \
-	--without-groundingline \
+	--without-modules \
 	--without-kriging  \
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
-	#--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install
Index: /issm/branches/trunk-jpl-damage/configure.ac
===================================================================
--- /issm/branches/trunk-jpl-damage/configure.ac	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/configure.ac	(revision 13101)
@@ -4,6 +4,8 @@
 AC_INIT([ISSM],[4.2.1],[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
+AC_CONFIG_MACRO_DIR([externalpackages/libtool/install/share/aclocal])                 #m4 macros are located in m4
+m4_include([m4/issm_options.m4])
 AC_CANONICAL_TARGET                       #Determine the system type
+
 #Compilers
 AC_PROG_CC([cccl cl icl gcc])
@@ -11,4 +13,5 @@
 AC_PROG_CXX([cccl cl icl g++])
 AC_PROG_F77([ifort g77 gfortran])
+
 #Libraries and linking
 AC_F77_LIBRARY_LDFLAGS
@@ -22,10 +25,7 @@
 AM_PROG_CC_C_O
 AM_PROG_AR
-AC_PROG_RANLIB 
 
-# To produce shared libraries uncomment LT_INIT. In theory, Libtool can be initialized
-# even if all linking is static, since, if not shared libraries are to be produce, libtool
-# will act simply as a wrapper around AR and Ranlib.
-#LT_INIT
+#Libtool
+LT_INIT
 
 #Run issm_options.m4
@@ -36,11 +36,8 @@
 			src/Makefile
 			src/c/Makefile 
-			src/py/Makefile
-			src/py/model/Makefile
 			src/modules/Makefile
 			src/modules/python/Makefile
 			src/modules/matlab/Makefile
-			src/m/Makefile
-			bin/Makefile])
+			src/m/Makefile])
 
 #End of configure.ac
Index: /issm/branches/trunk-jpl-damage/etc/environment.csh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment.csh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/etc/environment.csh	(revision 13101)
@@ -1,140 +1,97 @@
 #ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
-source $ISSM_DIR/etc/environment_variables.csh
 
-#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them before exporting the variables 
-#to environment.
-
-#foreach i ($@)
-#eval $i
-#end
-
-#CRON utilities
-setenv PATH {$PATH}:{$ISSM_DIR}/cron
-
-#SCRIPTS utilities
+#Load ISSM scripts
 setenv PATH {$PATH}:{$ISSM_DIR}/scripts
 
 #MATLAB
-setenv MATLAB_DIR {$MATLAB_DIR}
-setenv PATH {$MATLAB_DIR}/bin:{$PATH}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MATLAB_DIR/lib
+set MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+if (-d MATLAB_DIR) then
+	setenv MATLAB_DIR {$MATLAB_DIR}
+	setenv PATH {$MATLAB_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
+endif
 
 #MPI
-setenv MPI_DIR {$MPI_DIR}
-setenv PATH {$MPI_DIR}/bin:{$PATH}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
-setenv MANPATH {$MANPATH}:$MPI_DIR/man
-setenv MPIRUN_NPROCS 8
+set MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+if (-d $MPI_DIR) then
+	setenv MPI_DIR {$MPI_DIR}
+	setenv PATH {$MPI_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
+	setenv MANPATH {$MANPATH}:$MPI_DIR/man
+endif
 
 #PETSC
-setenv PETSC_DIR {$PETSC_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+set PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+if (-d $PETSC_DIR) then
+	setenv PETSC_DIR {$PETSC_DIR}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+endif
 
 #SLEPC
-setenv SLEPC_DIR {$SLEPC_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+set SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+if (-d $SLEPC_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+endif
 
+#PETSC
+set TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+if (-d $TAO_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$TAO_DIR/lib/{$ISSM_ARCH}
+endif
 
 #Dakota
-setenv DAKOTA_DIR {$DAKOTA_DIR}
-setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
-setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
-
-#Qhull
-setenv QHULL_DIR {$QHULL_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$QHULL_DIR}/lib
-
+set DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+if (-d $DAKOTA_DIR) then
+	setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
+	setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
+endif
 
 #Doxygen
-setenv DOXYGEN_DIR {$DOXYGEN_DIR}
-setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
-setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
-
-#MTOC
-setenv MTOC_DIR {$MTOC_DIR}
-setenv PATH {$PATH}:{$MTOC_DIR}
-
-#MATLAB
-setenv MATLAB_DIR {$MATLAB_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
-setenv PATH {$PATH}:{$MATLAB_DIR}/bin
-
-#TRIANGLE
-setenv TRIANGLE_DIR {$TRIANGLE_DIR}
-
-#METIS
-setenv METIS_DIR {$METIS_DIR}
-	
-#BLAS
-setenv BLAS_DIR {$BLAS_DIR}
-
-#LAPACK
-setenv LAPACK_DIR {$LAPACK_DIR}
-
-#SCALAPACK
-setenv SCALAPACK_DIR {$SCALAPACK_DIR}
-
-#PLAPACK
-setenv PLAPACK_DIR {$PLAPACK_DIR}
-
-#BLACS
-setenv BLACS_DIR {$BLACS_DIR}
-
-#YAMS
-setenv YAMS_DIR {$YAMS_DIR}
-setenv PATH {$PATH}:{$YAMS_DIR}
-
-#TEX2IM
-setenv TEX2IM_DIR {$TEX2IM_DIR}
-setenv PATH {$PATH}:{$TEX2IM_DIR}
-
-#SOWING
-setenv SOWING_DIR {$SOWING_DIR}
-setenv PATH {$PATH}:{$SOWING_DIR}/bin
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$SOWING_DIR}/lib
-setenv MANPATH {$MANPATH}:{$SOWING_DIR}/man
-
-#Chaco
-setenv CHACO_DIR {$CHACO_DIR}
-setenv PATH {$PATH}:{$CHACO_DIR}
-
-#MeshPart
-setenv MESHPART_DIR {$MESHPART_DIR}
-setenv PATH {$PATH}:{$MESHPART_DIR}
-
-#SCOTCH
-setenv SCOTCH_DIR {$SCOTCH_DIR}
-setenv PATH {$PATH}:{$SCOTCH_DIR}
-setenv MANPATH {$MANPATH}:{$SCOTCH_DIR}/man
+set DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+if (-d $DOXYGEN_DIR) then
+	setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
+	setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
+endif
 
 #AUTOCONF
-setenv AUTOCONF_DIR {$AUTOCONF_DIR}
-setenv PATH {$AUTOCONF_DIR}/bin:{$PATH}
+set AUTOCONF_DIR="$ISSM_DIR/externalpackages/autoconf/install"
+if (-d $AUTOCONF_DIR) then
+	setenv PATH {$AUTOCONF_DIR}/bin:{$PATH}
+endif
 
 #AUTOMAKE
-setenv AUTOMAKE_DIR {$AUTOMAKE_DIR}
-setenv PATH {$AUTOMAKE_DIR}/bin:{$PATH}
-
-#BORLAND
-setenv BORLAND_DIR {$BORLAND_DIR}
-setenv PATH {$PATH}:{$BORLAND_DIR}/Bin
+set AUTOMAKE_DIR="$ISSM_DIR/externalpackages/automake/install"
+if (-d $AUTOMAKE_DIR) then
+	setenv PATH {$AUTOMAKE_DIR}/bin:{$PATH}
+endif
 
 #SSH
-setenv SSH_DIR {$SSH_DIR}
-setenv PATH {$PATH}:{$SSH_DIR}
+set SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+if (-d $SSH_DIR) then
+	setenv PATH {$PATH}:{$SSH_DIR}
+endif
 
 #VALGRIND
-setenv VALGRIND_DIR {$VALGRIND_DIR}
-setenv PATH {$PATH}:{$VALGRIND_DIR}
+set VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install/bin"
+if (-d $VALGRIND_DIR) then
+	setenv PATH {$PATH}:{$VALGRIND_DIR}
+endif
 
 #MERCURIAL
-#setenv PYTHONPATH {$PYTHONPATH}:{$MERCURIAL_DIR}/mercurial/pure/
-setenv PYTHONPATH {$MERCURIAL_DIR}/mercurial/pure/
-setenv PATH {$PATH}:{$MERCURIAL_DIR}
+set MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if (-d $MERCURIAL_DIR) then
+	setenv PYTHONPATH {$MERCURIAL_DIR}/mercurial/pure/
+	setenv PATH {$PATH}:{$MERCURIAL_DIR}
+endif
 
 #GSL
-setenv GSL_DIR {$GSL_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$GSL_DIR}/lib
+set GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+if (-d $GSL_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$GSL_DIR}/lib
+endif
 
 #CMAKE
-setenv PATH {$PATH}:{$CMAKE_DIR}/bin
+set CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+if (-d $CMAKE_DIR) then
+	setenv PATH {$PATH}:{$CMAKE_DIR}/bin
+endif
Index: /issm/branches/trunk-jpl-damage/etc/environment.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/etc/environment.sh	(revision 13101)
@@ -1,3 +1,8 @@
 #ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+#FIXME: during installation packages are installed one by one but environment.sh was sourced
+#before so new packages are NOT in the path.
+#may resource environment.sh with:
+#if [ -z $(echo "$PATH" | grep "$MATLAB_DIR") ]; then export $PATH...; fi
 
 #Windows compilers: 
@@ -6,293 +11,352 @@
 fi
 
-source $ISSM_DIR/etc/environment_variables.sh
-
-#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them after exporting the variables
-#to environment.
-for i in $@
-do
-	eval $i
-done
-
-#CRON utilities
-PATH="$PATH:$ISSM_DIR/cron"
-
-#scripts
-PATH="$PATH:$ISSM_DIR/scripts"
-
-##MATLAB
-export MATLAB_DIR
-PATH="$MATLAB_DIR/bin:$PATH" #take precedence over /usr/local/bin/matlab
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/lib"
-#export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/bin/glnxa64"
-#export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/bin/glnxa64"
-
-#MPI
-export MPI_DIR
-PATH="$MPI_DIR/bin:$PATH"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MPI_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$MPI_DIR/lib"
-export MANPATH="$MANPATH:$MPI_DIR/man"
-export MPIRUN_NPROCS=24
-
-#PETSC
-export PETSC_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib/$ISSM_ARCH:$PETSC_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
-
-#SLEPC
-export SLEPC_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
-export LD_RUN_PATH="$LD_RUN_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
-
-#Dakota
-export DAKOTA_DIR
-PATH="$PATH:$DAKOTA_DIR/bin"
-export MANPATH="$MANPATH:$MPI_DIR/man:$DAKOTA_DIR/docs/man:$DAKOTA_DIR/docs/man-ref"
-
-#Qhull
-export QHULL_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QHULL_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$QHULL_DIR/lib"
-
-#Doxygen
-export DOXYGEN_DIR
-MANPATH="$MANPATH:$DOXYGEN_DIR/man"
-PATH="$PATH:$DOXYGEN_DIR/bin"
-
-#MTOC
-export MTOC_DIR
-PATH="$PATH:$MTOC_DIR"
-
-#TRIANGLE
-export TRIANGLE_DIR
-
-#METIS
-export METIS_DIR
-	
-#BLAS
-export BLAS_DIR
-
-#LAPACK
-export LAPACK_DIR
-
-#SCALAPACK
-export SCALAPACK_DIR
-
-#PLAPACK
-export PLAPACK_DIR
-
-#BLACS
-export BLACS_DIR
-
-#YAMS
-export YAMS_DIR
-PATH="$PATH:$YAMS_DIR"
-
-#BAMG
-export BAMG_DIR
-PATH="$PATH:$BAMG_DIR"
-
-#TEX2IM
-export TEX2IM_DIR
-PATH="$PATH:$TEX2IM_DIR"
-
-#SOWING
-export SOWING_DIR
-PATH="$PATH:$SOWING_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SOWING_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$SOWING_DIR/lib"
-export MANPATH="$MANPATH:$SOWING_DIR/man"
-
-#Chaco
-export CHACO_DIR
-PATH="$PATH:$CHACO_DIR"
-
-#MeshPart
-export MESHPART_DIR
-PATH="$PATH:$MESHPART_DIR"
-
-#SCOTCH
-export SCOTCH_DIR
-PATH="$PATH:$SCOTCH_DIR"
-export MANPATH="$MANPATH:$SCOTCH_DIR/man"
-
-#AUTOCONF
-export AUTOCONF_DIR
-PATH="$AUTOCONF_DIR/bin:$PATH"
-
-#AUTOMAKE
-export AUTOMAKE_DIR
-PATH="$AUTOMAKE_DIR/bin:$PATH"
-
-export LIBTOOL_DIR
-PATH="$LIBTOOL_DIR/bin:$PATH"
-
-#BORLAND
-export BORLAND_DIR
-PATH="$PATH:$BORLAND_DIR/Bin"
-
-#INTEL
-#export INTEL_DIR
-#PATH="$PATH:$INTEL_DIR"
-#source $ISSM_DIR/externalpackages/intel/intel.sh
-
-#SDK
-export SDK_DIR
-PATH="$PATH:$SDK_DIR"
-
-#SSH
-export SSH_DIR
-PATH="$PATH:$SSH_DIR"
-
-#VALGRIND
-export VALGRIND_DIR
-PATH="$PATH:$VALGRIND_DIR"
-
-#GRAPHVIZ
-export GRAPHVIZ_DIR
-PATH="$PATH:$GRAPHVIZ_DIR"
-
-#CPPCHECK
-export CPPCHECK_DIR
-PATH="$PATH:$CPPCHECK_DIR"
-
-#GDAL
-export GDAL_DIR
-PATH="$GDAL_DIR/bin:$PATH"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GDAL_DIR/lib"
-
-#MERCURIAL
-export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
-export PATH="$PATH:$MERCURIAL_DIR/"
-
-#BOOST
-export BOOSTROOT
-export BOOST_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BOOST_DIR/lib"
-export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$BOOST_DIR/lib"
-export PATH="$PATH:$BOOST_DIR/bin"
-
-#XERCES
-export XERCESROOT 
-export XERCESCROOT
-
-#xaifBooster
-export XAIFBOOSTERROOT
-export XAIFBOOSTER_HOME
-export XAIF_DIR
-export PLATFORM
-
-#angel
-export ANGELROOT
-
-#openanalysis
-export OPENANALYSISROOT
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$OPENANALYSISROOT/lib"
-
-#JAVA
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JVM_DIR"
-
-#BBFTP
-export PATH="$PATH:$BBFTP_DIR/bin"
-
-#ADIC
-export PATH="$PATH:$ADIC_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ADIC_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$ADIC_DIR/lib"
-
-#COLPACK
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$COLPACK_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$COLPACK_DIR/lib"
-
-#ECLIPSE
-export PATH="$PATH:$ECLIPSE_DIR"
-
-#FLAIM
-export FLAIM_DIR
-
-#APPSCAN
-export PATH="$PATH:$APPSCAN_DIR/install/bin"
-export PATH="$PATH:$APPSCAN_DIR/bin"
-
-#CPPCHECK
-export PATH="$PATH:$CPPCHECK_DIR/bin"
-
-#RATS
-export PATH="$PATH:$RATS_DIR/bin"
-
-#DYSON
-export PATH="$PATH:$DYSON_DIR"
-
-#CMAKE
-export PATH="$PATH:$CMAKE_DIR/bin"
-
-#SHAPELIB
-export PATH="$PATH:$SHAPELIB_DIR/exec"
-
-#CCCL
-export PATH="$PATH:$CCCL_DIR/bin"
-
-#PACKAGEMAKER
-export PATH="$PATH:$PACKAGEMAKER_DIR"
-
-#ANDROID_NDK:
-export ANDROID_NDK_DIR
-export PATH="$PATH:$ANDROID_NDK_DIR/"
-
-#ANDROID_DIR
-export ANDROID_DIR
-
-#ANDROID_SDK
-export PATH="$PATH:$ANDROID_SDK_DIR/"
-
-#ANDROID_ANT
-export PATH="$PATH:$ANDROID_ANT_DIR/"
-
-#GSL
-export PATH="$PATH:$GSL_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GSL_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$GSL_DIR/lib"
-
-#GMAKE
-export PATH="$GMAKE_DIR/bin:$PATH"
-
-#PYTHON
-export PATH="$PYTHON_DIR/bin:$PATH"
-export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/src/modules/python"
-export LD_LIBRARY_PATH=$ISSM_DIR/src/modules/python:$ISSM_DIR/externalpackages/python/install/lib:$LD_LIBRARY_PATH
-export PYTHONSTARTUP
-
-#MODELE
-export PATH="$MODELE_DIR/src/exec:$PATH"
-
-#GIT
-export PATH="$PATH:$GIT_DIR/install/bin"
-
-#NCVIEW
-export PATH="$PATH:$NCVIEW_DIR/install"
-
-#TCLX
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TCLX_DIR"
-export LD_RUN_PATH="$LD_RUN_PATH:$TCLX_DIR"
-
-#TCL/TK
+#Some basic path, in case it is not included by default
 export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib"
 export LD_RUN_PATH="$LD_RUN_PATH:/usr/local/lib"
 
+#Load ISSM scripts
+export PATH="$PATH:$ISSM_DIR/scripts"
+
+#MATLAB
+MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+#if [ -d "$MATLAB_DIR" ]; then
+	export MATLAB_DIR
+	export PATH="$MATLAB_DIR/bin:$PATH" #take precedence over /usr/local/bin/matlab
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/lib"
+#fi
+
+#MPI
+MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+#if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	export PATH="$MPI_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MPI_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$MPI_DIR/lib"
+	export MANPATH="$MANPATH:$MPI_DIR/man"
+#fi
+
+#PETSC
+PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+#if [ -d "$PETSC_DIR" ]; then
+	export PETSC_DIR
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib:$PETSC_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$PETSC_DIR/lib"
+#fi
+
+#SLEPC
+SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+if [ -d "$SLEPC_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
+	export LD_RUN_PATH="$LD_RUN_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
+fi
+
+#PETSC
+TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+if [ -d "$TAO_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TAO_DIR/lib:$TAO_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$TAO_DIR/lib"
+fi
+
+#Dakota
+DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+if [ -d "$DAKOTA_DIR" ]; then
+	export PATH="$PATH:$DAKOTA_DIR/bin"
+	export MANPATH="$MANPATH:$MPI_DIR/man:$DAKOTA_DIR/docs/man:$DAKOTA_DIR/docs/man-ref"
+fi
+
+#Doxygen
+DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+if [ -d "$DOXYGEN_DIR" ]; then
+	export MANPATH="$MANPATH:$DOXYGEN_DIR/man"
+	export PATH="$PATH:$DOXYGEN_DIR/bin"
+fi
+
+#AUTOCONF
+AUTOCONF_DIR="$ISSM_DIR/externalpackages/autoconf/install"
+#if [ -d "$AUTOCONF_DIR" ]; then
+	export PATH="$AUTOCONF_DIR/bin:$PATH"
+#fi
+
+#AUTOMAKE
+AUTOMAKE_DIR="$ISSM_DIR/externalpackages/automake/install"
+#if [ -d "$AUTOMAKE_DIR" ]; then
+	export PATH="$AUTOMAKE_DIR/bin:$PATH"
+#fi
+
+#LIBTOOL
+LIBTOOL_DIR="$ISSM_DIR/externalpackages/libtool/install"
+#if [ -d "$LIBTOOL_DIR" ]; then
+	export PATH="$LIBTOOL_DIR/bin:$PATH"
+#fi
+
+#SDK
+SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+if [ -d "$SDK_DIR" ]; then
+	export PATH="$PATH:$SDK_DIR"
+fi
+
+#SSH
+SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+if [ -d "$SSH_DIR" ]; then
+	export PATH="$PATH:$SSH_DIR"
+fi
+
+#VALGRIND
+VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install"
+if [ -d "$VALGRIND_DIR" ]; then
+	export PATH="$VALGRIND_DIR/bin:$PATH"
+fi
+
+#CPPCHECK
+CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
+if [ -d "$CPPCHECK_DIR" ]; then
+	export PATH="$PATH:$CPPCHECK_DIR/bin"
+fi
+
+#GDAL
+GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
+if [ -d "$GDAL_DIR" ]; then
+	export PATH="$GDAL_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GDAL_DIR/lib"
+fi
+
+#MERCURIAL
+MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if [ -d "$MERCURIAL_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+	export PATH="$PATH:$MERCURIAL_DIR/"
+fi
+
+#BOOST
+BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if [ -d "$BOOST_DIR" ]; then
+	export BOOSTROOT
+	export BOOST_DIR
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BOOST_DIR/lib"
+	export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$BOOST_DIR/lib"
+	export PATH="$PATH:$BOOST_DIR/bin"
+fi
+
+#XERCES
+XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
+if [ -d "$XERCESROOT" ]; then
+	export XERCESROOT 
+	export XERCESCROOT
+fi
+
+#xaifBooster
+XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
+XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+PLATFORM="x86-Linux"
+if [ -d "$XAIF_DIR" ]; then
+	export XAIFBOOSTERROOT
+	export XAIFBOOSTER_HOME
+	export XAIF_DIR
+	export PLATFORM
+fi
+
+#angel
+ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
+if [ -d "$ANGELROOT" ]; then
+	export ANGELROOT
+fi
+
+#openanalysis
+OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
+if [ -d "$OPENANALYSISROOT" ]; then
+	export OPENANALYSISROOT
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$OPENANALYSISROOT/lib"
+fi
+
+#JAVA
+JVM_DIR="/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/"
+if [ -d "$JVM_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JVM_DIR"
+fi
+
+#BBFTP
+BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
+if [ -d "$BBFTP_DIR" ]; then
+	export PATH="$PATH:$BBFTP_DIR/bin"
+fi
+
+#ADIC
+ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
+if [ -d "$ADIC_DIR" ]; then
+	export PATH="$PATH:$ADIC_DIR/bin"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ADIC_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$ADIC_DIR/lib"
+fi
+
+#COLPACK
+COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
+if [ -d "$COLPACK_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$COLPACK_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$COLPACK_DIR/lib"
+fi
+
+#ECLIPSE
+ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
+if [ -d "$ECLIPSE_DIR" ]; then
+	export PATH="$PATH:$ECLIPSE_DIR"
+fi
+
+#APPSCAN
+APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan/install"
+if [ -d "$APPSCAN_DIR" ]; then
+	export PATH="$PATH:$APPSCAN_DIR/bin"
+fi
+
+#RATS
+RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
+if [ -d "$RATS_DIR" ]; then
+	export PATH="$PATH:$RATS_DIR/bin"
+fi
+
+#DYSON
+DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
+if [ -d "$DYSON_DIR" ]; then
+	export PATH="$PATH:$DYSON_DIR"
+fi
+
+#CMAKE
+CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+if [ -d "$CMAKE_DIR" ]; then
+	export PATH="$PATH:$CMAKE_DIR/bin"
+fi
+
+#SHAPELIB
+SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
+if [ -d "$SHAPELIB_DIR" ]; then
+	export PATH="$PATH:$SHAPELIB_DIR/exec"
+fi
+
+#CCCL
+CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
+if [ -d "$CCCL_DIR" ]; then
+	export PATH="$PATH:$CCCL_DIR/bin"
+fi
+
+#PACKAGEMAKER
+PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
+if [ -d "$PACKAGEMAKER_DIR" ]; then
+	export PATH="$PATH:$PACKAGEMAKER_DIR"
+fi
+
+#ANDROID_NDK:
+ANDROID_NDK_DIR="$ISSM_DIR/externalpackages/android-ndk/install"
+if [ -d "$ANDROID_NDK_DIR" ]; then
+	export PATH="$PATH:$ANDROID_NDK_DIR/"
+fi
+
+#ANDROID_SDK
+ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install-sdk"
+if [ -d "$ANDROID_SDK_DIR" ]; then
+	export PATH="$PATH:$ANDROID_SDK_DIR/"
+fi
+
+#GSL
+GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+if [ -d "$GSL_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GSL_DIR/lib"
+	export LD_RUN_PATH="$LD_RUN_PATH:$GSL_DIR/lib"
+fi
+
+#GMAKE
+GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
+if [ -d "$GMAKE_DIR" ]; then
+	export PATH="$GMAKE_DIR/bin:$PATH"
+fi
+
+#PYTHON
+PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
+if [ -d "$PYTHON_DIR" ]; then
+	PYTHONSTARTUP="$ISSM_DIR/startup.py"
+	export PATH="$PYTHON_DIR/bin:$PATH"
+	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/src/modules/python"
+	export LD_LIBRARY_PATH=$ISSM_DIR/src/modules/python:$ISSM_DIR/externalpackages/python/install/lib:$LD_LIBRARY_PATH
+	export PYTHONSTARTUP="$ISSM_DIR/startup.py"
+fi
+
+#MODELE
+MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
+if [ -d "$MODELE_DIR" ]; then
+	export PATH="$MODELE_DIR/src/exec:$PATH"
+fi
+
+#GIT
+GIT_DIR="$ISSM_DIR/externalpackages/git/install"
+if [ -d "$GIT_DIR" ]; then
+	export PATH="$PATH:$GIT_DIR/bin"
+fi
+
+#NCVIEW
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
+if [ -d "$NCVIEW_DIR" ]; then
+	export PATH="$PATH:$NCVIEW_DIR"
+fi
+
+#TCLX
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+if [ -d "$TCLX_DIR" ]; then
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TCLX_DIR"
+	export LD_RUN_PATH="$LD_RUN_PATH:$TCLX_DIR"
+fi
+
 #ASPELL
-export PATH="$ASPELL_DIR/install/bin:$PATH"
-
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/install"
+if [ -d "$ASPELL_DIR" ]; then
+	export PATH="$ASPELL_DIR/bin:$PATH"
+fi
 
 #ESMF
-export ESMF_DIR=$ISSM_DIR/externalpackages/esmf/esmf
-export ESMF_COMPILER=gfortran
-export ESMF_COMM=mpich2
+ESMF_DIR="$ISSM_DIR/externalpackages/esmf/esmf"
+if [ -d "$ESMF_DIR" ]; then
+	export ESMF_COMPILER=gfortran
+	export ESMF_COMM=mpich2
+fi
 
 #HDF5
-export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$HDF5_DIR/lib"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HDF5_DIR/lib"
-export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
-export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
-
+HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+if [ -d "$HDF5_DIR" ]; then
+	export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$HDF5_DIR/lib"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HDF5_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+fi
+
+#SVN
+SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
+if [ -d "$SVN_DIR" ]; then
+	export PATH="$SVN_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SVN_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$SVN_DIR/lib"
+fi
+
+#APR
+APR_DIR="$ISSM_DIR/externalpackages/apr/install"
+if [ -d "$APR_DIR" ]; then
+	export PATH="$APR_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$APR_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$APR_DIR/lib"
+fi
+
+#APR_UTIL
+APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
+if [ -d "$APR_UTIL_DIR" ]; then
+	export PATH="$APR_UTIL_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$APR_UTIL_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$APR_UTIL_DIR/lib"
+fi
+
+#SQLITE
+SQLITE_DIR="$ISSM_DIR/externalpackages/sqlite/install"
+if [ -d "$SQLITE_DIR" ]; then
+	export PATH="$SQLITE_DIR/bin:$PATH"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SQLITE_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$SQLITE_DIR/lib"
+fi
Index: sm/branches/trunk-jpl-damage/etc/environment_variables.csh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment_variables.csh	(revision 13100)
+++ 	(revision )
@@ -1,93 +1,0 @@
-#
-#
-#This routine can only be run if the ISSM_DIR variable has been correctly set!
-#
-#
-
-#MATLAB
-set MATLAB_DIR={$ISSM_DIR}/externalpackages/matlab/install
-
-#MPI
-set MPI_DIR={$ISSM_DIR}/externalpackages/mpich2/install
-
-#PETSC
-set PETSC_DIR={$ISSM_DIR}/externalpackages/petsc/install
-
-#SLEPC
-set SLEPC_DIR={$ISSM_DIR}/externalpackages/slepc/install
-
-#Dakota
-set DAKOTA_DIR={$ISSM_DIR}/externalpackages/dakota/install
-
-#Qhull
-set QHULL_DIR={$ISSM_DIR}/externalpackages/qhull/install
-
-#Doxygen
-set DOXYGEN_DIR={$ISSM_DIR}/externalpackages/doxygen/install
-
-#MTOC
-set MTOC_DIR={$ISSM_DIR}/externalpackages/mtoc/install
-
-#Triangle
-set TRIANGLE_DIR={$ISSM_DIR}/externalpackages/triangle/install
-
-#METIS
-set METIS_DIR={$ISSM_DIR}/externalpackages/metis/install
-
-#BLAS
-set BLAS_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/fblaslapack
-
-#LAPACK
-set LAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/fblaslapack/$ISSM_ARCH
-
-#SCALAPACK
-set SCALAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/SCALAPACK/$ISSM_ARCH
-
-#PLAPACK
-set PLAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/PLAPACKR32
-
-#BLACS
-set BLACS_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/blacs-dev/$ISSM_ARCH
-
-#sowing
-set SOWING_DIR={$ISSM_DIR}/externalpackages/sowing/install
-
-#YAMS
-set YAMS_DIR={$ISSM_DIR}/externalpackages/yams/install
-
-#TEX2IM
-set TEX2IM_DIR={$ISSM_DIR}/externalpackages/tex2im/install
-
-#Chaco
-set CHACO_DIR={$ISSM_DIR}/externalpackages/chaco/install
-
-#MeshPart
-set MESHPART_DIR={$ISSM_DIR}/externalpackages/meshpart/install
-
-#SCOTCH
-set SCOTCH_DIR={$ISSM_DIR}/externalpackages/scotch/install
-
-#Development packages
-#automake
-set AUTOMAKE_DIR={$ISSM_DIR}/externalpackages/automake/install
-
-#autoconf
-set AUTOCONF_DIR={$ISSM_DIR}/externalpackages/autoconf/install
-
-#borland
-set BORLAND_DIR=/cygdrive/c/Borland
-
-#ssh
-set SSH_DIR={$ISSM_DIR}/externalpackages/ssh
-
-#mercurial
-set MERCURIAL_DIR={$ISSM_DIR}/externalpackages/mercurial/install
-
-#valgrind
-set VALGRIND_DIR={$ISSM_DIR}/externalpackages/valgrind/install/bin
-
-#gsl
-set GSL_DIR={$ISSM_DIR}/externalpackages/gsl/install
-
-#cmake
-set CMAKE_DIR={$ISSM_DIR}/externalpackages/cmake/install
Index: sm/branches/trunk-jpl-damage/etc/environment_variables.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment_variables.sh	(revision 13100)
+++ 	(revision )
@@ -1,212 +1,0 @@
-#
-#
-#This routine can only be run if the ISSM_DIR variable has been correctly set!
-#
-#
-
-#MATLAB
-MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
-
-#MPI
-MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
-
-#PETSC
-PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
-
-#SLEPC
-SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
-
-#Dakota
-DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
-
-#Qhull
-QHULL_DIR="$ISSM_DIR/externalpackages/qhull/install"
-
-#Doxygen
-DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
-
-#MTOC
-MTOC_DIR="$ISSM_DIR/externalpackages/mtoc/install"
-
-#Triangle
-TRIANGLE_DIR="$ISSM_DIR/externalpackages/triangle/install"
-
-#METIS
-METIS_DIR="$ISSM_DIR/externalpackages/metis/install"
-
-#BLAS
-BLAS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/fblaslapack"
-
-#LAPACK
-LAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/fblaslapack/$ISSM_ARCH"
-
-#SCALAPACK
-SCALAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/SCALAPACK/$ISSM_ARCH"
-
-#PLAPACK
-PLAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32"
-
-#BLACS
-BLACS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
-
-#sowing
-SOWING_DIR="$ISSM_DIR/externalpackages/sowing/install"
-
-#BLACS
-BLACS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
-
-#YAMS
-YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
-
-#BAMG
-BAMG_DIR="$ISSM_DIR/externalpackages/bamg/install"
-
-#Chaco
-CHACO_DIR="$ISSM_DIR/externalpackages/chaco/install"
-
-#MeshPart
-MESHPART_DIR="$ISSM_DIR/externalpackages/meshpart/install"
-
-#SCOTCH
-SCOTCH_DIR="$ISSM_DIR/externalpackages/scotch/install"
-
-#Development packages
-#automake
-AUTOMAKE_DIR="$ISSM_DIR/externalpackages/automake/install"
-
-#libtool
-LIBTOOL_DIR="$ISSM_DIR/externalpackages/libtool/install"
-
-#autoconf
-AUTOCONF_DIR="$ISSM_DIR/externalpackages/autoconf/install"
-
-#borland
-#BORLAND_DIR="/cygdrive/c/Borland/"
-
-#intel
-#INTEL_DIR="C:/IntelInstall/Compiler/11.1/038/bin/ia32/"
-
-#TEX2IM			 
-TEX2IM_DIR="$ISSM_DIR/externalpackages/tex2im/install" 
-
-#sdk
-#SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
-
-#ssh 
-SSH_DIR="$ISSM_DIR/externalpackages/ssh"
-
-#valgrind
-VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install/bin"
-
-#graphviz
-GRAPHVIZ_DIR="$ISSM_DIR/externalpackages/graphviz/install/bin"
-
-#cppcheck
-CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
-
-#gdal
-GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
-
-#mercurial
-MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
-
-#boost
-BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
-BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
-
-#OpenAnalysis
-OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
-
-#xerces
-XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
-XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
-
-#xaifBooster
-XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
-XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
-XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
-PLATFORM=x86-Linux
-
-#angel
-ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
-
-#java
-JVM_DIR=/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/
-
-#bbftp
-BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
-
-#adic2
-ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
-
-#colpack
-COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
-
-#eclipse
-ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
-
-#flaim
-FLAIM_DIR="$ISSM_DIR/externalpackages/flaim/install"
-
-#appscan
-APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan"
-
-#cppcheck
-CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
-
-#rats
-RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
-
-#dyson
-DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
-
-#cmake
-CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
-
-#shapelib
-SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
-
-#cccl
-CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
-
-#packagemaker
-PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
-
-#android-dev-dir
-ANDROID_DIR="$ISSM_DIR/externalpackages/android"
-
-#android-ndk
-ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
-
-#android-sdk
-ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install-sdk"
-
-#gsl
-GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
-
-#gnu make
-GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
-
-#PYTHON
-PYTHON_VER=2.7
-PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
-PYTHONSTARTUP="$ISSM_DIR/startup.py"
-
-#MODELE
-MODELE_DIR="$ISSM_DIR/externalpackages/modelE"
-
-
-#GIT
-GIT_DIR="$ISSM_DIR/externalpackages/git"
-
-#NCVIEW
-NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview"
-
-#TCLX
-TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
-
-#ASPELL
-ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/"
-
-#HDF5
-export HDF5_DIR=$ISSM_DIR/externalpackages/hdf5/install
Index: /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-dev.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-dev.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-dev.sh	(revision 13101)
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
+
+#Some cleanup
+rm -rf install ADOL-C-2.2.0 trunk
+
+#Create install directories
+mkdir install
+
+svn co https://projects.coin-or.org/svn/ADOL-C/trunk
+
+#Compile ADOL-C
+cd trunk 
+
+autoconf
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install \
+#	--enable-sparse \
+#	--enable-docexa \
+#	--enable-addexa \
+#	--disable-shave
+
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/branches/trunk-jpl-damage/externalpackages/adolc/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-macosx64.sh	(revision 13100)
+++ 	(revision )
@@ -1,61 +1,0 @@
-#!/bin/bash
-
-#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
-
-#Some cleanup
-rm -rf install ADOL-C-2.2.0 src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
-
-#Create install directories
-mkdir install src
-
-#Untar 
-tar -zxvf  ADOL-C-2.2.0.tar.gz
-
-#Move ADOL-C into install directory
-mv ADOL-C-2.2.0/* src
-rm -rf ADOL-C-2.2.0
-
-#Compile ADOL-C
-cd src 
-
-#export CC=gcc
-#export CXX=g++
-#export CFLAGS="-arch x86_64"
-#export CXXFLAGS="-arch x86_64"
-
-./configure \
-	--prefix=$ISSM_DIR/externalpackages/adolc/install \
-	--enable-sparse \
-	--enable-docexa \
-	--enable-addexa \
-	--disable-shave
-
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-
-#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
-#in all Makefiles
-for i in `find ./ -name Makefile `
-do
-	echo $i
-	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
-	mv $i.bak $i
-done
-
-#remake: 
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-
Index: /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 13101)
@@ -4,11 +4,11 @@
 
 #Some cleanup
-rm -rf install ADOL-C-2.2.0 src
+rm -rf install ADOL-C-2.2.0 src trunk
+
+#Create install directories
+mkdir install src
 
 #Download from ISSM server
 $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
-
-#Create install directories
-mkdir install src
 
 #Untar 
@@ -19,11 +19,12 @@
 rm -rf ADOL-C-2.2.0
 
+
 #Compile ADOL-C
 cd src 
 
-export CC=gcc
-export CXX=g++
-export CFLAGS="-arch x86_64"
-export CXXFLAGS="-arch x86_64"
+#export CC=gcc
+#export CXX=g++
+#export CFLAGS="-arch x86_64"
+#export CXXFLAGS="-arch x86_64"
 
 ./configure \
@@ -40,2 +41,22 @@
 fi
 make install
+
+
+#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
+#in all Makefiles
+for i in `find ./ -name Makefile `
+do
+	echo $i
+	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
+	mv $i.bak $i
+done
+
+#remake: 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+
Index: /issm/branches/trunk-jpl-damage/externalpackages/apr-util/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/apr-util/install.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/apr-util/install.sh	(revision 13101)
@@ -0,0 +1,29 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-util-1.4.1
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-util-1.4.1.tar.gz' 'apr-util-1.4.1.tar.gz'
+
+#Untar 
+tar -zxvf  apr-util-1.4.1.tar.gz
+
+#Move apr-util into src directory
+mv apr-util-1.4.1/* src
+rm -rf apr-util-1.4.1
+
+#Configure apr-util
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr-util/install" --with-apr="$ISSM_DIR/externalpackages/apr/install"
+
+#Compile and install apr-util
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/apr/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/apr/install.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/apr/install.sh	(revision 13101)
@@ -0,0 +1,29 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-1.4.6
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-1.4.6.tar.gz' 'apr-1.4.6.tar.gz'
+
+#Untar 
+tar -zxvf  apr-1.4.6.tar.gz
+
+#Move apr into src directory
+mv apr-1.4.6/* src
+rm -rf apr-1.4.6
+
+#Configure apr
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr/install" 
+
+#Compile and install apr
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 13101)
@@ -5,5 +5,5 @@
 
 #Select or create a new simlink
-ln -s /usr/local/pkgs/matlab-7.6/ install
+#ln -s /usr/local/pkgs/matlab-7.6/ install
 #ln -s /discover/vis/mathworks/matlab_r2011b/ install
 #ln -s /usr/local/matlab704/ install
Index: /issm/branches/trunk-jpl-damage/externalpackages/pysvn/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/pysvn/install.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/pysvn/install.sh	(revision 13101)
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf pysvn-1.7.6
+mkdir src 
+
+export CC=/usr/local/gfortran/bin/gcc
+export CXX=/usr/local/gfortran/bin/g++
+export FFLAGS=-ff2c
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/pysvn-1.7.6.tar.gz' 'pysvn-1.7.6.tar.gz'
+
+#Untar 
+tar -zxvf  pysvn-1.7.6.tar.gz
+
+#Move pysvn into src directory
+mv pysvn-1.7.6/* src
+rm -rf pysvn-1.7.6
+
+$install
+cd src
+python setup.py build
+python setup.py install
Index: /issm/branches/trunk-jpl-damage/externalpackages/sqlite/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/sqlite/install.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/sqlite/install.sh	(revision 13101)
@@ -0,0 +1,29 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf sqlite-autoconf-3071300
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/sqlite-autoconf-3071300.tar.gz' 'sqlite-autoconf-3071300.tar.gz'
+
+#Untar 
+tar -zxvf  sqlite-autoconf-3071300.tar.gz
+
+#Move sqlite-autoconf into src directory
+mv sqlite-autoconf-3071300/* src
+rm -rf sqlite-autoconf-3071300
+
+#Configure sqlite-autoconf
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/sqlite/install" 
+
+#Compile and install sqlite-autoconf
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/svn/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/svn/install.sh	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/externalpackages/svn/install.sh	(revision 13101)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf subversion-1.6.18
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/subversion-1.6.18.tar.gz' 'subversion-1.6.18.tar.gz'
+
+#Untar 
+tar -zxvf  subversion-1.6.18.tar.gz
+
+#Move subversion into src directory
+mv subversion-1.6.18/* src
+rm -rf subversion-1.6.18
+
+#Configure subversion
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/svn/install" \
+	--with-swig="$ISSM_DIR/externalpackages/swig/install"  \
+	PYTHON2="$ISSM_DIR/externalpackages/python/install/bin/python" \
+	--with-sqlite="$ISSM_DIR/externalpackages/sqlite/install"
+
+#Compile and install subversion
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/swig/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/swig/install.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/swig/install.sh	(revision 13101)
@@ -21,9 +21,16 @@
 export LDFLAGS="-L$ISSM_DIR/externalpackages/pcre/install/.libs/"
 export LIBS="-lpcre"
-#Configure doxygen
+#Configure swig
 ./configure \
- --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --prefix="$ISSM_DIR/externalpackages/swig/install" \
  --with-pcre-prefix="$ISSM_DIR/externalpackages/pcre/install" \
- --with-pcre-exec-prefix="$ISSM_DIR/externalpackages/pcre/install"
-make 
+ --with-pcre-exec-prefix="$ISSM_DIR/externalpackages/pcre/install" \
+ --with-python="$ISSM_DIR/externalpackages/python/install/bin/python"
+
+#Compile and install gdal
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
 make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 13101)
@@ -6,9 +6,9 @@
 cat c.vim | sed "/ISSM's Enums begin/,/vim: ts=8/d" > temp
 echo "\"ISSM's Enums begin" >> temp
-cat ../../../../../src/c/EnumDefinitions/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[aA-zZ]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
+cat ../../../../../src/c/EnumDefinitions/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-z]Enum," -e "[A-Z]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
 echo "\"ISSM's Enums end" >> temp
 cat c.vim | sed "1,/ISSM's Enums end/d" >> temp
-
 mv temp c.vim
+exit 1
 
 #Synchronize objects
@@ -16,4 +16,5 @@
 echo "\"ISSM's objects begin" >> temp
 find ../../../../../src/c/classes -name "*.h" | sed -e "s/\// /g" -e "s/\.h//"| awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
+echo "\"ISSM's objects end" >> temp
 cat c.vim | sed "1,/ISSM's objects end/d" >> temp
 
Index: /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13101)
@@ -408,160 +408,160 @@
 syn keyword	cType		Vec Mat SeqVec SeqMat
 "other ISSM's syntax
-syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble
+syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble Observations
 
 "ISSM's objects begin
-syn keyword cType AdjacentTriangle
-syn keyword cType BamgGeom
-syn keyword cType BamgMesh
-syn keyword cType bamgobjects
-syn keyword cType BamgOpts
-syn keyword cType BamgQuadtree
-syn keyword cType BamgVertex
-syn keyword cType CrackedEdge
-syn keyword cType Curve
-syn keyword cType Direction
-syn keyword cType DoubleAndInt
-syn keyword cType Edge
-syn keyword cType GeomEdge
-syn keyword cType Geometry
-syn keyword cType GeomSubDomain
-syn keyword cType GeomVertex
-syn keyword cType include
-syn keyword cType ListofIntersectionTriangles
-syn keyword cType macros
-syn keyword cType Mesh
-syn keyword cType Metric
-syn keyword cType R2
-syn keyword cType SetOfE4
-syn keyword cType SubDomain
-syn keyword cType Triangle
-syn keyword cType typedefs
-syn keyword cType VertexOnEdge
-syn keyword cType VertexOnGeom
-syn keyword cType VertexOnVertex
-syn keyword cType classes
-syn keyword cType DakotaPlugin
-syn keyword cType DofIndexing
-syn keyword cType FemModel
+syn keyword cType GaussPenta
 syn keyword cType gaussobjects
-syn keyword cType GaussPenta
 syn keyword cType GaussTria
-syn keyword cType Hook
-syn keyword cType IoModel
-syn keyword cType ExponentialVariogram
-syn keyword cType GaussianVariogram
-syn keyword cType krigingobjects
-syn keyword cType Observation
-syn keyword cType PowerVariogram
-syn keyword cType Quadtree
-syn keyword cType SphericalVariogram
-syn keyword cType Variogram
-syn keyword cType ElementMatrix
-syn keyword cType ElementVector
-syn keyword cType Matrix
-syn keyword cType matrixobjects
-syn keyword cType Vector
-syn keyword cType Constraint
+syn keyword cType objects
+syn keyword cType Material
+syn keyword cType Matice
+syn keyword cType Matpar
+syn keyword cType objects
+syn keyword cType Contour
+syn keyword cType DoubleInput
+syn keyword cType Input
+syn keyword cType ControlInput
+syn keyword cType DatasetInput
+syn keyword cType IntInput
+syn keyword cType BoolInput
+syn keyword cType TriaP1Input
+syn keyword cType TransientInput
+syn keyword cType PentaP1Input
+syn keyword cType KML_Icon
+syn keyword cType KML_Point
+syn keyword cType KML_LinearRing
+syn keyword cType KML_Feature
+syn keyword cType KMLFileReadUtils
+syn keyword cType KML_StyleSelector
+syn keyword cType KML_LatLonBox
+syn keyword cType KML_Attribute
+syn keyword cType KML_PolyStyle
+syn keyword cType KML_Object
+syn keyword cType KML_SubStyle
+syn keyword cType KML_LineString
+syn keyword cType KML_Overlay
+syn keyword cType KML_Container
+syn keyword cType KML_Polygon
+syn keyword cType KML_Geometry
+syn keyword cType KML_ColorStyle
+syn keyword cType KML_Placemark
+syn keyword cType KML_Unknown
+syn keyword cType KML_GroundOverlay
+syn keyword cType KML_Style
+syn keyword cType KML_Comment
+syn keyword cType KML_MultiGeometry
+syn keyword cType KML_LineStyle
+syn keyword cType KML_Folder
+syn keyword cType KML_Document
+syn keyword cType KML_File
+syn keyword cType DoubleVecParam
+syn keyword cType DoubleParam
+syn keyword cType DoubleMatArrayParam
+syn keyword cType DoubleMatParam
+syn keyword cType Param
+syn keyword cType FileParam
+syn keyword cType IntVecParam
+syn keyword cType IntParam
+syn keyword cType BoolParam
+syn keyword cType IntMatParam
+syn keyword cType VectorParam
+syn keyword cType DoubleTransientMatParam
+syn keyword cType MatrixParam
+syn keyword cType StringArrayParam
+syn keyword cType StringParam
+syn keyword cType TransientParam
+syn keyword cType OptionStruct
+syn keyword cType OptionDouble
+syn keyword cType OptionLogical
+syn keyword cType OptionUtilities
+syn keyword cType OptionChar
+syn keyword cType Option
+syn keyword cType OptionCell
+syn keyword cType Segment
+syn keyword cType Icefront
+syn keyword cType Friction
+syn keyword cType Riftfront
+syn keyword cType Numericalflux
+syn keyword cType Penpair
+syn keyword cType Load
+syn keyword cType Pengrid
+syn keyword cType Object
+syn keyword cType DoubleVecExternalResult
+syn keyword cType DoubleExternalResult
+syn keyword cType IntExternalResult
+syn keyword cType BoolExternalResult
+syn keyword cType DoubleMatExternalResult
+syn keyword cType PetscVecExternalResult
+syn keyword cType ExternalResult
+syn keyword cType StringExternalResult
+syn keyword cType Vertex
 syn keyword cType SpcDynamic
 syn keyword cType SpcStatic
 syn keyword cType SpcTransient
-syn keyword cType Contour
+syn keyword cType Constraint
+syn keyword cType TriaP1ElementResult
+syn keyword cType PentaP1ElementResult
+syn keyword cType DoubleElementResult
+syn keyword cType ElementResultLocal
 syn keyword cType BoolElementResult
-syn keyword cType DoubleElementResult
 syn keyword cType ElementResult
-syn keyword cType ElementResultLocal
-syn keyword cType PentaP1ElementResult
-syn keyword cType TriaP1ElementResult
+syn keyword cType Node
+syn keyword cType TriaRef
+syn keyword cType TriaHook
+syn keyword cType PentaRef
+syn keyword cType PentaHook
+syn keyword cType Tria
 syn keyword cType Element
 syn keyword cType Penta
-syn keyword cType PentaHook
-syn keyword cType PentaRef
-syn keyword cType Tria
-syn keyword cType TriaHook
-syn keyword cType TriaRef
-syn keyword cType BoolExternalResult
-syn keyword cType DoubleExternalResult
-syn keyword cType DoubleMatExternalResult
-syn keyword cType DoubleVecExternalResult
-syn keyword cType ExternalResult
-syn keyword cType IntExternalResult
-syn keyword cType PetscVecExternalResult
-syn keyword cType StringExternalResult
-syn keyword cType BoolInput
-syn keyword cType ControlInput
-syn keyword cType DatasetInput
-syn keyword cType DoubleInput
-syn keyword cType Input
-syn keyword cType IntInput
-syn keyword cType PentaP1Input
-syn keyword cType TransientInput
-syn keyword cType TriaP1Input
-syn keyword cType KML_Attribute
-syn keyword cType KML_ColorStyle
-syn keyword cType KML_Comment
-syn keyword cType KML_Container
-syn keyword cType KML_Document
-syn keyword cType KML_Feature
-syn keyword cType KML_File
-syn keyword cType KML_Folder
-syn keyword cType KML_Geometry
-syn keyword cType KML_GroundOverlay
-syn keyword cType KML_Icon
-syn keyword cType KML_LatLonBox
-syn keyword cType KML_LinearRing
-syn keyword cType KML_LineString
-syn keyword cType KML_LineStyle
-syn keyword cType KML_MultiGeometry
-syn keyword cType KML_Object
-syn keyword cType KML_Overlay
-syn keyword cType KML_Placemark
-syn keyword cType KML_Point
-syn keyword cType KML_Polygon
-syn keyword cType KML_PolyStyle
-syn keyword cType KML_Style
-syn keyword cType KML_StyleSelector
-syn keyword cType KML_SubStyle
-syn keyword cType KML_Unknown
-syn keyword cType KMLFileReadUtils
-syn keyword cType Friction
-syn keyword cType Icefront
-syn keyword cType Load
-syn keyword cType Numericalflux
-syn keyword cType Pengrid
-syn keyword cType Penpair
-syn keyword cType Riftfront
-syn keyword cType Material
-syn keyword cType Matice
-syn keyword cType Matpar
-syn keyword cType Node
-syn keyword cType Object
-syn keyword cType objects
-syn keyword cType Option
-syn keyword cType OptionCell
-syn keyword cType OptionChar
-syn keyword cType OptionDouble
-syn keyword cType OptionLogical
-syn keyword cType OptionStruct
-syn keyword cType OptionUtilities
-syn keyword cType BoolParam
-syn keyword cType DoubleMatArrayParam
-syn keyword cType DoubleMatParam
-syn keyword cType DoubleParam
-syn keyword cType DoubleTransientMatParam
-syn keyword cType DoubleVecParam
-syn keyword cType FileParam
-syn keyword cType IntMatParam
-syn keyword cType IntParam
-syn keyword cType IntVecParam
-syn keyword cType MatrixParam
-syn keyword cType Param
-syn keyword cType StringArrayParam
-syn keyword cType StringParam
-syn keyword cType TransientParam
-syn keyword cType VectorParam
-syn keyword cType Segment
-syn keyword cType Vertex
-syn keyword cType objects
+syn keyword cType classes
+syn keyword cType DofIndexing
+syn keyword cType Patch
+syn keyword cType Hook
+syn keyword cType Quadtree
+syn keyword cType Observation
+syn keyword cType ExponentialVariogram
+syn keyword cType GaussianVariogram
+syn keyword cType SphericalVariogram
+syn keyword cType PowerVariogram
+syn keyword cType krigingobjects
+syn keyword cType Variogram
+syn keyword cType DakotaPlugin
+syn keyword cType ElementVector
+syn keyword cType ElementMatrix
+syn keyword cType matrixobjects
+syn keyword cType Vector
+syn keyword cType Matrix
+syn keyword cType GeomSubDomain
+syn keyword cType Geometry
+syn keyword cType AdjacentTriangle
+syn keyword cType VertexOnEdge
+syn keyword cType BamgQuadtree
+syn keyword cType Edge
+syn keyword cType BamgVertex
+syn keyword cType SetOfE4
+syn keyword cType GeomEdge
+syn keyword cType Direction
+syn keyword cType VertexOnGeom
+syn keyword cType R2
+syn keyword cType Mesh
+syn keyword cType ListofIntersectionTriangles
+syn keyword cType Triangle
+syn keyword cType DoubleAndInt
+syn keyword cType VertexOnVertex
+syn keyword cType BamgOpts
+syn keyword cType BamgGeom
+syn keyword cType bamgobjects
+syn keyword cType CrackedEdge
+syn keyword cType SubDomain
+syn keyword cType BamgMesh
+syn keyword cType Metric
+syn keyword cType include
+syn keyword cType typedefs
+syn keyword cType Curve
+syn keyword cType macros
+syn keyword cType GeomVertex
 syn keyword cType OptArgs
+syn keyword cType Update
 syn keyword cType OptPars
 syn keyword cType BamgOpts
Index: /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vimrc	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vimrc	(revision 13101)
@@ -203,4 +203,6 @@
 au BufRead,BufNewFile *.c*       iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
 au BufRead,BufNewFile *.c*,*.h   iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.py       iabbr <silent> ER  raise NameError('')<Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m        iabbr <silent> ER  error('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
 au BufRead,BufNewFile *.c*       ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
 au BufRead,BufNewFile *.c*       ab AS _assert_();
Index: /issm/branches/trunk-jpl-damage/ltmain.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/ltmain.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/ltmain.sh	(revision 13101)
@@ -1,8 +1,8 @@
-# Generated from ltmain.m4sh.
-
-# ltmain.sh (GNU libtool) 2.2.6b
+
+# libtool (GNU libtool) 2.4.2
 # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
 
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc.
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
 # This is free software; see the source for copying conditions.  There is NO
 # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
@@ -33,27 +33,32 @@
 # Provide generalized library-building support services.
 #
-#     --config             show all configuration variables
-#     --debug              enable verbose shell tracing
-# -n, --dry-run            display commands without modifying any files
-#     --features           display basic configuration information and exit
-#     --mode=MODE          use operation mode MODE
-#     --preserve-dup-deps  don't remove duplicate dependency libraries
-#     --quiet, --silent    don't print informational messages
-#     --tag=TAG            use configuration variables from tag TAG
-# -v, --verbose            print informational messages (default)
-#     --version            print version information
-# -h, --help               print short or long help message
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and exit
+#       --mode=MODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --no-warn            don't display warning messages
+#       --tag=TAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
 #
 # MODE must be one of the following:
 #
-#       clean              remove files from the build directory
-#       compile            compile a source file into a libtool object
-#       execute            automatically set library path, then run a program
-#       finish             complete the installation of libtool libraries
-#       install            install libraries or executables
-#       link               create a library or an executable
-#       uninstall          remove libraries from an installed directory
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a program
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
 #
-# MODE-ARGS vary depending on the MODE.
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
 # Try `$progname --help --mode=MODE' for a more detailed description of MODE.
 #
@@ -61,20 +66,22 @@
 # include the following information:
 #
-#       host-triplet:	$host
-#       shell:		$SHELL
-#       compiler:		$LTCC
-#       compiler flags:		$LTCFLAGS
-#       linker:		$LD (gnu? $with_gnu_ld)
-#       $progname:		(GNU libtool) 2.2.6b
-#       automake:		$automake_version
-#       autoconf:		$autoconf_version
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4.2
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
 #
 # Report bugs to <bug-libtool@gnu.org>.
-
-PROGRAM=ltmain.sh
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=libtool
 PACKAGE=libtool
-VERSION=2.2.6b
+VERSION=2.4.2
 TIMESTAMP=""
-package_revision=1.3017
+package_revision=1.3337
 
 # Be Bourne compatible
@@ -92,8 +99,13 @@
 DUALCASE=1; export DUALCASE # for MKS sh
 
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
 # NLS nuisances: We save the old values to restore during execute mode.
-# Only set LANG and LC_ALL to C if already set.
-# These must not be set unconditionally because not all systems understand
-# e.g. LANG=C (notably SCO).
 lt_user_locale=
 lt_safe_locale=
@@ -108,22 +120,26 @@
 	fi"
 done
+LC_ALL=C
+LANGUAGE=C
+export LANGUAGE LC_ALL
 
 $lt_unset CDPATH
 
 
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
 
 
 
 : ${CP="cp -f"}
-: ${ECHO="echo"}
-: ${EGREP="/bin/grep -E"}
-: ${FGREP="/bin/grep -F"}
-: ${GREP="/bin/grep"}
-: ${LN_S="ln -s"}
+test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
 : ${MAKE="make"}
 : ${MKDIR="mkdir"}
 : ${MV="mv -f"}
 : ${RM="rm -f"}
-: ${SED="/bin/sed"}
 : ${SHELL="${CONFIG_SHELL-/bin/sh}"}
 : ${Xsed="$SED -e 1s/^X//"}
@@ -144,4 +160,25 @@
 dirname="s,/[^/]*$,,"
 basename="s,^.*/,,"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
 
 # func_dirname_and_basename file append nondir_replacement
@@ -159,31 +196,181 @@
 func_dirname_and_basename ()
 {
-  # Extract subdirectory from the argument.
-  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
-  if test "X$func_dirname_result" = "X${1}"; then
-    func_dirname_result="${3}"
-  else
-    func_dirname_result="$func_dirname_result${2}"
+    # Extract subdirectory from the argument.
+    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementation
+
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+    case ${2} in
+      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar='s,^/\([^/]*\).*$,\1,'
+pathcdr='s,^/[^/]*,,'
+removedotparts=':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes='s@/\{1,\}@/@g'
+finalslash='s,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=
+  func_normal_abspath_tpath=$1
+  func_normal_abspath_altnamespace=
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" = / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+        func_relative_path_tcancelled=$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" = x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=../$func_relative_path_result
+          func_relative_path_tcancelled=$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" != x ; then
+    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
   fi
-  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
-}
-
-# Generated shell functions inserted here.
-
-# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
-# is ksh but when the shell is invoked as "sh" and the current value of
-# the _XPG environment variable is not equal to 1 (one), the special
-# positional parameter $0, within a function call, is the name of the
-# function.
-progpath="$0"
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=$func_stripname_result
+  fi
+}
 
 # The name of this program:
-# In the unlikely event $progname began with a '-', it would play havoc with
-# func_echo (imagine progname=-n), so we prepend ./ in that case:
 func_dirname_and_basename "$progpath"
 progname=$func_basename_result
-case $progname in
-  -*) progname=./$progname ;;
-esac
 
 # Make sure we have an absolute path for reexecution:
@@ -197,5 +384,5 @@
   *)
      save_IFS="$IFS"
-     IFS=:
+     IFS=${PATH_SEPARATOR-:}
      for progdir in $PATH; do
        IFS="$save_IFS"
@@ -215,4 +402,13 @@
 # Same as above, but do not quote variable references.
 double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
 
 # Re-`\' parameter expansions in output of double_quote_subst that were
@@ -244,5 +440,5 @@
 func_echo ()
 {
-    $ECHO "$progname${mode+: }$mode: $*"
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
 }
 
@@ -259,9 +455,16 @@
 }
 
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
 # func_error arg...
 # Echo program name prefixed message to standard error.
 func_error ()
 {
-    $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
 }
 
@@ -270,5 +473,5 @@
 func_warning ()
 {
-    $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
 
     # bash bug again:
@@ -327,7 +530,7 @@
 
         # ...otherwise throw away the child directory and loop
-        my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"`
+        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
       done
-      my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'`
+      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
 
       save_mkdir_p_IFS="$IFS"; IFS=':'
@@ -379,5 +582,5 @@
     fi
 
-    $ECHO "X$my_tmpdir" | $Xsed
+    $ECHO "$my_tmpdir"
 }
 
@@ -393,5 +596,5 @@
     case $1 in
       *[\\\`\"\$]*)
-	func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;;
+	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
       *)
         func_quote_for_eval_unquoted_result="$1" ;;
@@ -420,5 +623,5 @@
     case $1 in
       *[\\\`\"]*)
-	my_arg=`$ECHO "X$1" | $Xsed \
+	my_arg=`$ECHO "$1" | $SED \
 	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
       *)
@@ -489,6 +692,20 @@
 }
 
-
-
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=$1
+    ;;
+  esac
+}
 
 
@@ -497,5 +714,15 @@
 func_version ()
 {
-    $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / {
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
         s/^# //
 	s/^# *$//
@@ -510,5 +737,7 @@
 func_usage ()
 {
-    $SED -n '/^# Usage:/,/# -h/ {
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
         s/^# //
 	s/^# *$//
@@ -516,14 +745,18 @@
 	p
     }' < "$progpath"
-    $ECHO
+    echo
     $ECHO "run \`$progname --help | more' for full usage"
     exit $?
 }
 
-# func_help
-# Echo long help message to standard output and exit.
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
 func_help ()
 {
+    $opt_debug
+
     $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
         s/^# //
 	s/^# *$//
@@ -535,9 +768,16 @@
 	s*\$LD*'"$LD"'*
 	s/\$with_gnu_ld/'"$with_gnu_ld"'/
-	s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/
-	s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/
+	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
 	p
-     }' < "$progpath"
-    exit $?
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=$?
+    if test -z "$1"; then
+      exit $ret
+    fi
 }
 
@@ -547,8 +787,36 @@
 func_missing_arg ()
 {
-    func_error "missing argument for $1"
+    $opt_debug
+
+    func_error "missing argument for $1."
     exit_cmd=exit
 }
 
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
+    my_sed_long_arg='1s/^--[^=]*=//'
+
+    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
 exit_cmd=:
 
@@ -556,28 +824,4 @@
 
 
-
-# Check that we have a working $ECHO.
-if test "X$1" = X--no-reexec; then
-  # Discard the --no-reexec flag, and continue.
-  shift
-elif test "X$1" = X--fallback-echo; then
-  # Avoid inline document here, it may be left over
-  :
-elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then
-  # Yippee, $ECHO works!
-  :
-else
-  # Restart under the correct shell, and then maybe $ECHO will work.
-  exec $SHELL "$progpath" --no-reexec ${1+"$@"}
-fi
-
-if test "X$1" = X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<EOF
-$*
-EOF
-  exit $EXIT_SUCCESS
-fi
 
 magic="%%%MAGIC variable%%%"
@@ -585,7 +829,5 @@
 
 # Global variables.
-# $mode is unset
 nonopt=
-execute_dlfiles=
 preserve_args=
 lo2o="s/\\.lo\$/.${objext}/"
@@ -594,9 +836,4 @@
 extracted_serial=0
 
-opt_dry_run=false
-opt_duplicate_deps=false
-opt_silent=false
-opt_debug=:
-
 # If this variable is set in any of the actions, the command in it
 # will be execed at the end.  This prevents here-documents from being
@@ -604,4 +841,50 @@
 exec_cmd=
 
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
 # func_fatal_configuration arg...
 # Echo program name prefixed message to standard error, followed by
@@ -637,14 +920,14 @@
 func_features ()
 {
-    $ECHO "host: $host"
+    echo "host: $host"
     if test "$build_libtool_libs" = yes; then
-      $ECHO "enable shared libraries"
+      echo "enable shared libraries"
     else
-      $ECHO "disable shared libraries"
+      echo "disable shared libraries"
     fi
     if test "$build_old_libs" = yes; then
-      $ECHO "enable static libraries"
+      echo "enable static libraries"
     else
-      $ECHO "disable static libraries"
+      echo "disable static libraries"
     fi
 
@@ -691,131 +974,4 @@
       ;;
   esac
-}
-
-# Parse options once, thoroughly.  This comes as soon as possible in
-# the script to make things like `libtool --version' happen quickly.
-{
-
-  # Shorthand for --mode=foo, only valid as the first argument
-  case $1 in
-  clean|clea|cle|cl)
-    shift; set dummy --mode clean ${1+"$@"}; shift
-    ;;
-  compile|compil|compi|comp|com|co|c)
-    shift; set dummy --mode compile ${1+"$@"}; shift
-    ;;
-  execute|execut|execu|exec|exe|ex|e)
-    shift; set dummy --mode execute ${1+"$@"}; shift
-    ;;
-  finish|finis|fini|fin|fi|f)
-    shift; set dummy --mode finish ${1+"$@"}; shift
-    ;;
-  install|instal|insta|inst|ins|in|i)
-    shift; set dummy --mode install ${1+"$@"}; shift
-    ;;
-  link|lin|li|l)
-    shift; set dummy --mode link ${1+"$@"}; shift
-    ;;
-  uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
-    shift; set dummy --mode uninstall ${1+"$@"}; shift
-    ;;
-  esac
-
-  # Parse non-mode specific arguments:
-  while test "$#" -gt 0; do
-    opt="$1"
-    shift
-
-    case $opt in
-      --config)		func_config					;;
-
-      --debug)		preserve_args="$preserve_args $opt"
-			func_echo "enabling shell trace mode"
-			opt_debug='set -x'
-			$opt_debug
-			;;
-
-      -dlopen)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			execute_dlfiles="$execute_dlfiles $1"
-			shift
-			;;
-
-      --dry-run | -n)	opt_dry_run=:					;;
-      --features)       func_features					;;
-      --finish)		mode="finish"					;;
-
-      --mode)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			case $1 in
-			  # Valid mode arguments:
-			  clean)	;;
-			  compile)	;;
-			  execute)	;;
-			  finish)	;;
-			  install)	;;
-			  link)		;;
-			  relink)	;;
-			  uninstall)	;;
-
-			  # Catch anything else as an error
-			  *) func_error "invalid argument for $opt"
-			     exit_cmd=exit
-			     break
-			     ;;
-		        esac
-
-			mode="$1"
-			shift
-			;;
-
-      --preserve-dup-deps)
-			opt_duplicate_deps=:				;;
-
-      --quiet|--silent)	preserve_args="$preserve_args $opt"
-			opt_silent=:
-			;;
-
-      --verbose| -v)	preserve_args="$preserve_args $opt"
-			opt_silent=false
-			;;
-
-      --tag)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			preserve_args="$preserve_args $opt $1"
-			func_enable_tag "$1"	# tagname is set here
-			shift
-			;;
-
-      # Separate optargs to long options:
-      -dlopen=*|--mode=*|--tag=*)
-			func_opt_split "$opt"
-			set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"}
-			shift
-			;;
-
-      -\?|-h)		func_usage					;;
-      --help)		opt_help=:					;;
-      --version)	func_version					;;
-
-      -*)		func_fatal_help "unrecognized option \`$opt'"	;;
-
-      *)		nonopt="$opt"
-			break
-			;;
-    esac
-  done
-
-
-  case $host in
-    *cygwin* | *mingw* | *pw32* | *cegcc*)
-      # don't eliminate duplications in $postdeps and $predeps
-      opt_duplicate_compiler_generated_deps=:
-      ;;
-    *)
-      opt_duplicate_compiler_generated_deps=$opt_duplicate_deps
-      ;;
-  esac
-
-  # Having warned about all mis-specified options, bail out if
-  # anything was wrong.
-  $exit_cmd $EXIT_FAILURE
 }
 
@@ -856,35 +1012,216 @@
 
 
+# Shorthand for --mode=foo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=:
+opt_dry_run=false
+opt_config=false
+opt_preserve_dup_deps=false
+opt_features=false
+opt_finish=false
+opt_help=false
+opt_help_all=false
+opt_silent=:
+opt_warning=:
+opt_verbose=:
+opt_silent=false
+opt_verbose=false
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt="$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug='set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=:
+			;;
+      --config)
+			opt_config=:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg="$1"
+			opt_dlopen="${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=:
+			;;
+      --features)
+			opt_features=:
+func_features
+			;;
+      --finish)
+			opt_finish=:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=:
+			;;
+      --help-all)
+			opt_help_all=:
+opt_help=': help-all'
+			;;
+      --mode)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_mode="$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=exit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=false
+func_append preserve_args " $opt"
+			;;
+      --no-warning|--no-warn)
+			opt_warning=false
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=false
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=:
+func_append preserve_args " $opt"
+        opt_verbose=false
+			;;
+      --verbose|-v)
+			opt_verbose=:
+func_append preserve_args " $opt"
+opt_silent=false
+			;;
+      --tag)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_tag="$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt="$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" = : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+      func_fatal_configuration "not configured to build any kind of library"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help="$help"
+    help="Try \`$progname --help --mode=$opt_mode' for more information."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
 ## ----------- ##
 ##    Main.    ##
 ## ----------- ##
-
-$opt_help || {
-  # Sanity checks first:
-  func_check_version_match
-
-  if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
-    func_fatal_configuration "not configured to build any kind of library"
-  fi
-
-  test -z "$mode" && func_fatal_error "error: you must specify a MODE."
-
-
-  # Darwin sucks
-  eval std_shrext=\"$shrext_cmds\"
-
-
-  # Only execute mode is allowed to have -dlopen flags.
-  if test -n "$execute_dlfiles" && test "$mode" != execute; then
-    func_error "unrecognized option \`-dlopen'"
-    $ECHO "$help" 1>&2
-    exit $EXIT_FAILURE
-  fi
-
-  # Change the help message to a mode-specific one.
-  generic_help="$help"
-  help="Try \`$progname --help --mode=$mode' for more information."
-}
-
 
 # func_lalib_p file
@@ -951,10 +1288,7 @@
 func_ltwrapper_scriptname ()
 {
-    func_ltwrapper_scriptname_result=""
-    if func_ltwrapper_executable_p "$1"; then
-	func_dirname_and_basename "$1" "" "."
-	func_stripname '' '.exe' "$func_basename_result"
-	func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
-    fi
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
 }
 
@@ -1002,4 +1336,35 @@
 
 
+# func_resolve_sysroot PATH
+# Replace a leading = in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=$1
+  case $func_resolve_sysroot_result in
+  =*)
+    func_stripname '=' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with = and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result="=$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=$1
+    ;;
+  esac
+}
+
 # func_infer_tag arg
 # Infer tagged configuration to use if any are available and
@@ -1014,11 +1379,13 @@
       CC_quoted=
       for arg in $CC; do
-        func_quote_for_eval "$arg"
-	CC_quoted="$CC_quoted $func_quote_for_eval_result"
+	func_append_quoted CC_quoted "$arg"
       done
+      CC_expanded=`func_echo_all $CC`
+      CC_quoted_expanded=`func_echo_all $CC_quoted`
       case $@ in
       # Blanks in the command may have been stripped by the calling shell,
       # but not from the CC environment variable when configure was run.
-      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;;
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
       # Blanks at the start of $base_compile will cause this to fail
       # if we don't check for them as well.
@@ -1031,9 +1398,11 @@
 	    for arg in $CC; do
 	      # Double-quote args containing other shell metacharacters.
-	      func_quote_for_eval "$arg"
-	      CC_quoted="$CC_quoted $func_quote_for_eval_result"
+	      func_append_quoted CC_quoted "$arg"
 	    done
+	    CC_expanded=`func_echo_all $CC`
+	    CC_quoted_expanded=`func_echo_all $CC_quoted`
 	    case "$@ " in
-	      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*)
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
 	      # The compiler in the base compile command matches
 	      # the one in the tagged configuration.
@@ -1098,4 +1467,484 @@
 }
 
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *nix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath program
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and will
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result="$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and print
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, and
+# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
+# configured wine environment available, with the winepath program in $build's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=""
+  if test -n "$1"; then
+    oldIFS=$IFS
+    IFS=:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file name
+# or path in func_cygpath_result (input file name or path is assumed to be in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or path to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=
+    fi
+  else
+    func_cygpath_result=
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result="$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" != "x$2"; then
+      lt_replace_pathsep_chars="s|$1|$2|g"
+      func_to_host_path_result=`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result="$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return result
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result="$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environment
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinations,
+# the two new functions must follow this pattern, or func_init_to_host_path_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result="$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment and
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
 # func_mode_compile arg...
 func_mode_compile ()
@@ -1138,10 +1987,10 @@
 
 	-pie | -fpie | -fPIE)
-          pie_flag="$pie_flag $arg"
+          func_append pie_flag " $arg"
 	  continue
 	  ;;
 
 	-shared | -static | -prefer-pic | -prefer-non-pic)
-	  later="$later $arg"
+	  func_append later " $arg"
 	  continue
 	  ;;
@@ -1164,6 +2013,5 @@
 	  for arg in $args; do
 	    IFS="$save_ifs"
-	    func_quote_for_eval "$arg"
-	    lastarg="$lastarg $func_quote_for_eval_result"
+	    func_append_quoted lastarg "$arg"
 	  done
 	  IFS="$save_ifs"
@@ -1172,5 +2020,5 @@
 
 	  # Add the arguments to base_compile.
-	  base_compile="$base_compile $lastarg"
+	  func_append base_compile " $lastarg"
 	  continue
 	  ;;
@@ -1188,6 +2036,5 @@
 
       # Aesthetically quote the previous argument.
-      func_quote_for_eval "$lastarg"
-      base_compile="$base_compile $func_quote_for_eval_result"
+      func_append_quoted base_compile "$lastarg"
     done # for arg
 
@@ -1214,5 +2061,5 @@
     *.ada | *.adb | *.ads | *.asm | \
     *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
-    *.[fF][09]? | *.for | *.java | *.obj | *.sx)
+    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
       func_xform "$libobj"
       libobj=$func_xform_result
@@ -1289,5 +2136,5 @@
     # not support -o with -c
     if test "$compiler_c_o" = no; then
-      output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
       lockfile="$output_obj.lock"
     else
@@ -1320,15 +2167,14 @@
 	exit $EXIT_FAILURE
       fi
-      removelist="$removelist $output_obj"
+      func_append removelist " $output_obj"
       $ECHO "$srcfile" > "$lockfile"
     fi
 
     $opt_dry_run || $RM $removelist
-    removelist="$removelist $lockfile"
+    func_append removelist " $lockfile"
     trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
 
-    if test -n "$fix_srcfile_path"; then
-      eval srcfile=\"$fix_srcfile_path\"
-    fi
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=$func_to_tool_file_result
     func_quote_for_eval "$srcfile"
     qsrcfile=$func_quote_for_eval_result
@@ -1350,5 +2196,5 @@
       if test -z "$output_obj"; then
 	# Place PIC objects in $objdir
-	command="$command -o $lobj"
+	func_append command " -o $lobj"
       fi
 
@@ -1397,9 +2243,9 @@
       fi
       if test "$compiler_c_o" = yes; then
-	command="$command -o $obj"
+	func_append command " -o $obj"
       fi
 
       # Suppress compiler output if we already did a PIC compilation.
-      command="$command$suppress_output"
+      func_append command "$suppress_output"
       func_show_eval_locale "$command" \
         '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
@@ -1446,5 +2292,5 @@
 
 $opt_help || {
-test "$mode" = compile && func_mode_compile ${1+"$@"}
+  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
 }
 
@@ -1452,5 +2298,5 @@
 {
     # We need to display help for each of the modes.
-    case $mode in
+    case $opt_mode in
       "")
         # Generic help is extracted from the usage comments
@@ -1483,8 +2329,9 @@
   -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
   -no-suppress      do not suppress compiler output for multiple passes
-  -prefer-pic       try to building PIC objects only
-  -prefer-non-pic   try to building non-PIC objects only
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
   -shared           do not build a \`.o' file suitable for static linking
   -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
 
 COMPILE-COMMAND is a command to be used in creating a \`standard' object file
@@ -1539,5 +2386,5 @@
 The following components of INSTALL-COMMAND are treated specially:
 
-  -inst-prefix PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
 
 The rest of the components are interpreted as arguments to that command (only
@@ -1559,4 +2406,6 @@
   -all-static       do not do any dynamic linking at all
   -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
   -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
   -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
@@ -1587,4 +2436,9 @@
                     specify library version info [each variable defaults to 0]
   -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
 
 All other options (arguments beginning with \`-') are ignored.
@@ -1620,16 +2474,42 @@
 
       *)
-        func_fatal_help "invalid operation mode \`$mode'"
+        func_fatal_help "invalid operation mode \`$opt_mode'"
         ;;
     esac
 
-    $ECHO
+    echo
     $ECHO "Try \`$progname --help' for more information about other modes."
-
-    exit $?
-}
-
-  # Now that we've collected a possible --mode arg, show help if necessary
-  $opt_help && func_mode_help
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" = :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
+      }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
 
 
@@ -1644,5 +2524,5 @@
 
     # Handle -dlopen flags immediately.
-    for file in $execute_dlfiles; do
+    for file in $opt_dlopen; do
       test -f "$file" \
 	|| func_fatal_help "\`$file' is not a file"
@@ -1651,4 +2531,7 @@
       case $file in
       *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
@@ -1672,5 +2555,5 @@
 
 	if test -f "$dir/$objdir/$dlname"; then
-	  dir="$dir/$objdir"
+	  func_append dir "/$objdir"
 	else
 	  if test ! -f "$dir/$dlname"; then
@@ -1713,5 +2596,5 @@
     do
       case $file in
-      -*) ;;
+      -* | *.la | *.lo ) ;;
       *)
 	# Do a test to see if this is really a libtool program.
@@ -1729,6 +2612,5 @@
       esac
       # Quote arguments (to preserve shell metacharacters).
-      func_quote_for_eval "$file"
-      args="$args $func_quote_for_eval_result"
+      func_append_quoted args "$file"
     done
 
@@ -1755,5 +2637,5 @@
       if test -n "$shlibpath_var"; then
 	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
-	$ECHO "export $shlibpath_var"
+	echo "export $shlibpath_var"
       fi
       $ECHO "$cmd$args"
@@ -1762,5 +2644,5 @@
 }
 
-test "$mode" = execute && func_mode_execute ${1+"$@"}
+test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
 
 
@@ -1769,13 +2651,50 @@
 {
     $opt_debug
-    libdirs="$nonopt"
+    libs=
+    libdirs=
     admincmds=
 
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
+        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+        done
+      else
+        tmpdir=`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
     if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
-      for dir
-      do
-	libdirs="$libdirs $dir"
-      done
-
       for libdir in $libdirs; do
 	if test -n "$finish_cmds"; then
@@ -1787,5 +2706,5 @@
 	  # Do the single finish_eval.
 	  eval cmds=\"$finish_eval\"
-	  $opt_dry_run || eval "$cmds" || admincmds="$admincmds
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
        $cmds"
 	fi
@@ -1796,51 +2715,53 @@
     $opt_silent && exit $EXIT_SUCCESS
 
-    $ECHO "X----------------------------------------------------------------------" | $Xsed
-    $ECHO "Libraries have been installed in:"
-    for libdir in $libdirs; do
-      $ECHO "   $libdir"
-    done
-    $ECHO
-    $ECHO "If you ever happen to want to link against installed libraries"
-    $ECHO "in a given directory, LIBDIR, you must either use libtool, and"
-    $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'"
-    $ECHO "flag during linking and do at least one of the following:"
-    if test -n "$shlibpath_var"; then
-      $ECHO "   - add LIBDIR to the \`$shlibpath_var' environment variable"
-      $ECHO "     during execution"
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "----------------------------------------------------------------------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=LIBDIR
+	eval flag=\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "----------------------------------------------------------------------"
     fi
-    if test -n "$runpath_var"; then
-      $ECHO "   - add LIBDIR to the \`$runpath_var' environment variable"
-      $ECHO "     during linking"
-    fi
-    if test -n "$hardcode_libdir_flag_spec"; then
-      libdir=LIBDIR
-      eval flag=\"$hardcode_libdir_flag_spec\"
-
-      $ECHO "   - use the \`$flag' linker flag"
-    fi
-    if test -n "$admincmds"; then
-      $ECHO "   - have your system administrator run these commands:$admincmds"
-    fi
-    if test -f /etc/ld.so.conf; then
-      $ECHO "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
-    fi
-    $ECHO
-
-    $ECHO "See any operating system documentation about shared libraries for"
-    case $host in
-      solaris2.[6789]|solaris2.1[0-9])
-        $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual"
-	$ECHO "pages."
-	;;
-      *)
-        $ECHO "more information, such as the ld(1) and ld.so(8) manual pages."
-        ;;
-    esac
-    $ECHO "X----------------------------------------------------------------------" | $Xsed
     exit $EXIT_SUCCESS
 }
 
-test "$mode" = finish && func_mode_finish ${1+"$@"}
+test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
 
 
@@ -1853,5 +2774,5 @@
     if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
        # Allow the use of GNU shtool's install command.
-       $ECHO "X$nonopt" | $GREP shtool >/dev/null; then
+       case $nonopt in *shtool*) :;; *) false;; esac; then
       # Aesthetically quote it.
       func_quote_for_eval "$nonopt"
@@ -1867,5 +2788,10 @@
     # Aesthetically quote it.
     func_quote_for_eval "$arg"
-    install_prog="$install_prog$func_quote_for_eval_result"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=: ;;
+      *) install_cp=false ;;
+    esac
 
     # We need to accept at least all the BSD install flags.
@@ -1877,8 +2803,10 @@
     isdir=no
     stripme=
+    no_mode=:
     for arg
     do
+      arg2=
       if test -n "$dest"; then
-	files="$files $dest"
+	func_append files " $dest"
 	dest=$arg
 	continue
@@ -1888,8 +2816,7 @@
       -d) isdir=yes ;;
       -f)
-	case " $install_prog " in
-	*[\\\ /]cp\ *) ;;
-	*) prev=$arg ;;
-	esac
+	if $install_cp; then :; else
+	  prev=$arg
+	fi
 	;;
       -g | -m | -o)
@@ -1905,4 +2832,8 @@
 	# If the previous option needed an argument, then skip it.
 	if test -n "$prev"; then
+	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	    arg2=$install_override_mode
+	    no_mode=false
+	  fi
 	  prev=
 	else
@@ -1915,5 +2846,9 @@
       # Aesthetically quote the argument.
       func_quote_for_eval "$arg"
-      install_prog="$install_prog $func_quote_for_eval_result"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
     done
 
@@ -1923,4 +2858,11 @@
     test -n "$prev" && \
       func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
 
     if test -z "$files"; then
@@ -1978,8 +2920,11 @@
       *.$libext)
 	# Do the static libraries later.
-	staticlibs="$staticlibs $file"
+	func_append staticlibs " $file"
 	;;
 
       *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
@@ -1995,5 +2940,5 @@
 	  case "$current_libdirs " in
 	  *" $libdir "*) ;;
-	  *) current_libdirs="$current_libdirs $libdir" ;;
+	  *) func_append current_libdirs " $libdir" ;;
 	  esac
 	else
@@ -2001,5 +2946,5 @@
 	  case "$future_libdirs " in
 	  *" $libdir "*) ;;
-	  *) future_libdirs="$future_libdirs $libdir" ;;
+	  *) func_append future_libdirs " $libdir" ;;
 	  esac
 	fi
@@ -2007,9 +2952,9 @@
 	func_dirname "$file" "/" ""
 	dir="$func_dirname_result"
-	dir="$dir$objdir"
+	func_append dir "$objdir"
 
 	if test -n "$relink_command"; then
 	  # Determine the prefix the user has applied to our future dir.
-	  inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"`
+	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
 
 	  # Don't allow the user to place us outside of our expected
@@ -2024,7 +2969,7 @@
 	  if test -n "$inst_prefix_dir"; then
 	    # Stick the inst_prefix_dir data into the link command.
-	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
 	  else
-	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"`
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
 	  fi
 
@@ -2044,5 +2989,5 @@
 
 	  # Install the shared library and build the symlinks.
-	  func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
 	      'exit $?'
 	  tstripme="$stripme"
@@ -2084,5 +3029,5 @@
 
 	# Maybe install the static library, too.
-	test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
 	;;
 
@@ -2184,5 +3129,5 @@
 	      func_source "$lib"
 	    fi
-	    libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
 	    if test -n "$libdir" && test ! -f "$libfile"; then
 	      func_warning "\`$lib' has not been installed in \`$libdir'"
@@ -2203,5 +3148,5 @@
 	        outputname="$tmpdir/$file"
 	        # Replace the output file specification.
-	        relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'`
+	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
 
 	        $opt_silent || {
@@ -2222,5 +3167,5 @@
 	  else
 	    # Install the binary that we compiled earlier.
-	    file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
 	  fi
 	fi
@@ -2258,9 +3203,11 @@
       # Set up the ranlib parameters.
       oldlib="$destdir/$name"
+      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+      tool_oldlib=$func_to_tool_file_result
 
       func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
 
       if test -n "$stripme" && test -n "$old_striplib"; then
-	func_show_eval "$old_striplib $oldlib" 'exit $?'
+	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
       fi
 
@@ -2281,5 +3228,5 @@
 }
 
-test "$mode" = install && func_mode_install ${1+"$@"}
+test "$opt_mode" = install && func_mode_install ${1+"$@"}
 
 
@@ -2324,4 +3271,20 @@
 #endif
 
+#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
 /* External symbol declarations for the compiler. */\
 "
@@ -2333,8 +3296,9 @@
 
 	  # Add our own program objects to the symbol list.
-	  progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	  for progfile in $progfiles; do
-	    func_verbose "extracting global C symbols from \`$progfile'"
-	    $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'"
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
 	  done
 
@@ -2372,5 +3336,5 @@
 	      eval '$MV "$nlist"T "$nlist"'
 	      case $host in
-	        *cygwin | *mingw* | *cegcc* )
+	        *cygwin* | *mingw* | *cegcc* )
 	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
 	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
@@ -2385,8 +3349,50 @@
 	  func_basename "$dlprefile"
 	  name="$func_basename_result"
-	  $opt_dry_run || {
-	    eval '$ECHO ": $name " >> "$nlist"'
-	    eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'"
-	  }
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename="$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import library>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
 	done
 
@@ -2416,8 +3422,8 @@
 	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
 	  else
-	    $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
 	  fi
 
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
+	  echo >> "$output_objdir/$my_dlsyms" "\
 
 /* The mapping between symbol names and symbols.  */
@@ -2426,24 +3432,7 @@
   void *address;
 } lt_dlsymlist;
-"
-	  case $host in
-	  *cygwin* | *mingw* | *cegcc* )
-	    $ECHO >> "$output_objdir/$my_dlsyms" "\
-/* DATA imports from DLLs on WIN32 con't be const, because
-   runtime relocations are performed -- see ld's documentation
-   on pseudo-relocs.  */"
-	    lt_dlsym_const= ;;
-	  *osf5*)
-	    echo >> "$output_objdir/$my_dlsyms" "\
-/* This system does not cope well with relocations in const data */"
-	    lt_dlsym_const= ;;
-	  *)
-	    lt_dlsym_const=const ;;
-	  esac
-
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
-extern $lt_dlsym_const lt_dlsymlist
+extern LT_DLSYM_CONST lt_dlsymlist
 lt_${my_prefix}_LTX_preloaded_symbols[];
-$lt_dlsym_const lt_dlsymlist
+LT_DLSYM_CONST lt_dlsymlist
 lt_${my_prefix}_LTX_preloaded_symbols[] =
 {\
@@ -2458,5 +3447,5 @@
 	    ;;
 	  esac
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
+	  echo >> "$output_objdir/$my_dlsyms" "\
   {0, (void *) 0}
 };
@@ -2485,5 +3474,5 @@
 	  # pic_flag when linking with -static.  The problem exists in
 	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
-	  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
 	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
 	  *-*-hpux*)
@@ -2501,5 +3490,5 @@
 	  case $arg in
 	  -pie | -fpie | -fPIE) ;;
-	  *) symtab_cflags="$symtab_cflags $arg" ;;
+	  *) func_append symtab_cflags " $arg" ;;
 	  esac
 	done
@@ -2516,14 +3505,14 @@
 	*cygwin* | *mingw* | *cegcc* )
 	  if test -f "$output_objdir/$my_outputname.def"; then
-	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
-	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
 	  else
-	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
-	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
 	  fi
 	  ;;
 	*)
-	  compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
-	  finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
 	  ;;
 	esac
@@ -2539,6 +3528,6 @@
 
       # Nullify the symbol file.
-      compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
-      finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
     fi
 }
@@ -2550,4 +3539,5 @@
 # Has to be a shell function in order to 'eat' the argument
 # that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
 func_win32_libid ()
 {
@@ -2560,7 +3550,9 @@
     ;;
   *ar\ archive*) # could be an import, or static
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
     if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
-       $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
-      win32_nmres=`eval $NM -f posix -A $1 |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
 	$SED -n -e '
 	    1,100{
@@ -2591,4 +3583,129 @@
 }
 
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/====MARK====/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^====MARK====/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^====MARK====/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^====MARK====//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=""
+  fi
+}
 
 
@@ -2599,5 +3716,16 @@
     f_ex_an_ar_dir="$1"; shift
     f_ex_an_ar_oldlib="$1"
-    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?'
+    if test "$lock_old_archive_extraction" = yes; then
+      lockfile=$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
+		   'stat=$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" = yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
     if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
      :
@@ -2670,5 +3798,5 @@
 	    darwin_files=
 	    for darwin_file in $darwin_filelist; do
-	      darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
 	      $LIPO -create -output "$darwin_file" $darwin_files
 	    done # $darwin_filelist
@@ -2685,244 +3813,9 @@
 	;;
       esac
-      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
     done
 
     func_extract_archives_result="$my_oldobjs"
 }
-
-
-
-# func_emit_wrapper_part1 [arg=no]
-#
-# Emit the first part of a libtool wrapper script on stdout.
-# For more information, see the description associated with
-# func_emit_wrapper(), below.
-func_emit_wrapper_part1 ()
-{
-	func_emit_wrapper_part1_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_part1_arg1=$1
-	fi
-
-	$ECHO "\
-#! $SHELL
-
-# $output - temporary wrapper script for $objdir/$outputname
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-#
-# The $output program cannot be directly executed until all the libtool
-# libraries that it depends on are installed.
-#
-# This wrapper script should never be moved out of the build directory.
-# If it is, it will not operate correctly.
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed='${SED} -e 1s/^X//'
-sed_quote_subst='$sed_quote_subst'
-
-# Be Bourne compatible
-if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
-fi
-BIN_SH=xpg4; export BIN_SH # for Tru64
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-relink_command=\"$relink_command\"
-
-# This environment variable determines our operation mode.
-if test \"\$libtool_install_magic\" = \"$magic\"; then
-  # install mode needs the following variables:
-  generated_by_libtool_version='$macro_version'
-  notinst_deplibs='$notinst_deplibs'
-else
-  # When we are sourced in execute mode, \$file and \$ECHO are already set.
-  if test \"\$libtool_execute_magic\" != \"$magic\"; then
-    ECHO=\"$qecho\"
-    file=\"\$0\"
-    # Make sure echo works.
-    if test \"X\$1\" = X--no-reexec; then
-      # Discard the --no-reexec flag, and continue.
-      shift
-    elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then
-      # Yippee, \$ECHO works!
-      :
-    else
-      # Restart under the correct shell, and then maybe \$ECHO will work.
-      exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
-    fi
-  fi\
-"
-	$ECHO "\
-
-  # Find the directory that this script lives in.
-  thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
-  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
-
-  # Follow symbolic links until we get to the real thisdir.
-  file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
-  while test -n \"\$file\"; do
-    destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
-
-    # If there was a directory component, then change thisdir.
-    if test \"x\$destdir\" != \"x\$file\"; then
-      case \"\$destdir\" in
-      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
-      *) thisdir=\"\$thisdir/\$destdir\" ;;
-      esac
-    fi
-
-    file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
-    file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
-  done
-"
-}
-# end: func_emit_wrapper_part1
-
-# func_emit_wrapper_part2 [arg=no]
-#
-# Emit the second part of a libtool wrapper script on stdout.
-# For more information, see the description associated with
-# func_emit_wrapper(), below.
-func_emit_wrapper_part2 ()
-{
-	func_emit_wrapper_part2_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_part2_arg1=$1
-	fi
-
-	$ECHO "\
-
-  # Usually 'no', except on cygwin/mingw when embedded into
-  # the cwrapper.
-  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1
-  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
-    # special case for '.'
-    if test \"\$thisdir\" = \".\"; then
-      thisdir=\`pwd\`
-    fi
-    # remove .libs from thisdir
-    case \"\$thisdir\" in
-    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;;
-    $objdir )   thisdir=. ;;
-    esac
-  fi
-
-  # Try to get the absolute directory name.
-  absdir=\`cd \"\$thisdir\" && pwd\`
-  test -n \"\$absdir\" && thisdir=\"\$absdir\"
-"
-
-	if test "$fast_install" = yes; then
-	  $ECHO "\
-  program=lt-'$outputname'$exeext
-  progdir=\"\$thisdir/$objdir\"
-
-  if test ! -f \"\$progdir/\$program\" ||
-     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
-       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
-
-    file=\"\$\$-\$program\"
-
-    if test ! -d \"\$progdir\"; then
-      $MKDIR \"\$progdir\"
-    else
-      $RM \"\$progdir/\$file\"
-    fi"
-
-	  $ECHO "\
-
-    # relink executable if necessary
-    if test -n \"\$relink_command\"; then
-      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
-      else
-	$ECHO \"\$relink_command_output\" >&2
-	$RM \"\$progdir/\$file\"
-	exit 1
-      fi
-    fi
-
-    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
-    { $RM \"\$progdir/\$program\";
-      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
-    $RM \"\$progdir/\$file\"
-  fi"
-	else
-	  $ECHO "\
-  program='$outputname'
-  progdir=\"\$thisdir/$objdir\"
-"
-	fi
-
-	$ECHO "\
-
-  if test -f \"\$progdir/\$program\"; then"
-
-	# Export our shlibpath_var if we have one.
-	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-	  $ECHO "\
-    # Add our own library path to $shlibpath_var
-    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
-
-    # Some systems cannot cope with colon-terminated $shlibpath_var
-    # The second colon is a workaround for a bug in BeOS R4 sed
-    $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
-
-    export $shlibpath_var
-"
-	fi
-
-	# fixup the dll searchpath if we need to.
-	if test -n "$dllsearchpath"; then
-	  $ECHO "\
-    # Add the dll search path components to the executable PATH
-    PATH=$dllsearchpath:\$PATH
-"
-	fi
-
-	$ECHO "\
-    if test \"\$libtool_execute_magic\" != \"$magic\"; then
-      # Run the actual program with our arguments.
-"
-	case $host in
-	# Backslashes separate directories on plain windows
-	*-*-mingw | *-*-os2* | *-cegcc*)
-	  $ECHO "\
-      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
-"
-	  ;;
-
-	*)
-	  $ECHO "\
-      exec \"\$progdir/\$program\" \${1+\"\$@\"}
-"
-	  ;;
-	esac
-	$ECHO "\
-      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
-      exit 1
-    fi
-  else
-    # The program doesn't exist.
-    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
-    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
-    $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
-    exit 1
-  fi
-fi\
-"
-}
-# end: func_emit_wrapper_part2
 
 
@@ -2943,186 +3836,299 @@
 func_emit_wrapper ()
 {
-	func_emit_wrapper_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_arg1=$1
-	fi
-
-	# split this up so that func_emit_cwrapperexe_src
-	# can call each part independently.
-	func_emit_wrapper_part1 "${func_emit_wrapper_arg1}"
-	func_emit_wrapper_part2 "${func_emit_wrapper_arg1}"
-}
-
-
-# func_to_host_path arg
+	func_emit_wrapper_arg1=${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
 #
-# Convert paths to host format when used with build tools.
-# Intended for use with "native" mingw (where libtool itself
-# is running under the msys shell), or in the following cross-
-# build environments:
-#    $build          $host
-#    mingw (msys)    mingw  [e.g. native]
-#    cygwin          mingw
-#    *nix + wine     mingw
-# where wine is equipped with the `winepath' executable.
-# In the native mingw case, the (msys) shell automatically
-# converts paths for any non-msys applications it launches,
-# but that facility isn't available from inside the cwrapper.
-# Similar accommodations are necessary for $host mingw and
-# $build cygwin.  Calling this function does no harm for other
-# $host/$build combinations not listed above.
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
 #
-# ARG is the path (on $build) that should be converted to
-# the proper representation for $host. The result is stored
-# in $func_to_host_path_result.
-func_to_host_path ()
-{
-  func_to_host_path_result="$1"
-  if test -n "$1" ; then
-    case $host in
-      *mingw* )
-        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-        case $build in
-          *mingw* ) # actually, msys
-            # awkward: cmd appends spaces to result
-            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
-            func_to_host_path_tmp1=`( cmd //c echo "$1" |\
-              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
-            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          *cygwin* )
-            func_to_host_path_tmp1=`cygpath -w "$1"`
-            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          * )
-            # Unfortunately, winepath does not exit with a non-zero
-            # error code, so we are forced to check the contents of
-            # stdout. On the other hand, if the command is not
-            # found, the shell will set an exit code of 127 and print
-            # *an error message* to stdout. So we must check for both
-            # error code of zero AND non-empty stdout, which explains
-            # the odd construction:
-            func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null`
-            if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then
-              func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-                $SED -e "$lt_sed_naive_backslashify"`
-            else
-              # Allow warning below.
-              func_to_host_path_result=""
-            fi
-            ;;
-        esac
-        if test -z "$func_to_host_path_result" ; then
-          func_error "Could not determine host path corresponding to"
-          func_error "  '$1'"
-          func_error "Continuing, but uninstalled executables may not work."
-          # Fallback:
-          func_to_host_path_result="$1"
-        fi
-        ;;
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    file=\"\$0\""
+
+    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=
+func_parse_lt_options ()
+{
+  lt_script_arg0=\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=1 ;;
+    --lt-dump-script)
+        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
+        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
+      ;;
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
+      ;;
+    esac
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+  fi
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+    ;;
+
+  *)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+    ;;
+  esac
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  case \" \$* \" in
+  *\\ --lt-*)
+    for lt_wr_arg
+    do
+      case \$lt_wr_arg in
+      --lt-*) ;;
+      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+      esac
+      shift
+    done ;;
+  esac
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
     esac
   fi
-}
-# end: func_to_host_path
-
-# func_to_host_pathlist arg
-#
-# Convert pathlists to host format when used with build tools.
-# See func_to_host_path(), above. This function supports the
-# following $build/$host combinations (but does no harm for
-# combinations not listed here):
-#    $build          $host
-#    mingw (msys)    mingw  [e.g. native]
-#    cygwin          mingw
-#    *nix + wine     mingw
-#
-# Path separators are also converted from $build format to
-# $host format. If ARG begins or ends with a path separator
-# character, it is preserved (but converted to $host format)
-# on output.
-#
-# ARG is a pathlist (on $build) that should be converted to
-# the proper representation on $host. The result is stored
-# in $func_to_host_pathlist_result.
-func_to_host_pathlist ()
-{
-  func_to_host_pathlist_result="$1"
-  if test -n "$1" ; then
-    case $host in
-      *mingw* )
-        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-        # Remove leading and trailing path separator characters from
-        # ARG. msys behavior is inconsistent here, cygpath turns them
-        # into '.;' and ';.', and winepath ignores them completely.
-        func_to_host_pathlist_tmp2="$1"
-        # Once set for this call, this variable should not be
-        # reassigned. It is used in tha fallback case.
-        func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\
-          $SED -e 's|^:*||' -e 's|:*$||'`
-        case $build in
-          *mingw* ) # Actually, msys.
-            # Awkward: cmd appends spaces to result.
-            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
-            func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\
-              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
-            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          *cygwin* )
-            func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"`
-            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          * )
-            # unfortunately, winepath doesn't convert pathlists
-            func_to_host_pathlist_result=""
-            func_to_host_pathlist_oldIFS=$IFS
-            IFS=:
-            for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do
-              IFS=$func_to_host_pathlist_oldIFS
-              if test -n "$func_to_host_pathlist_f" ; then
-                func_to_host_path "$func_to_host_pathlist_f"
-                if test -n "$func_to_host_path_result" ; then
-                  if test -z "$func_to_host_pathlist_result" ; then
-                    func_to_host_pathlist_result="$func_to_host_path_result"
-                  else
-                    func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result"
-                  fi
-                fi
-              fi
-              IFS=:
-            done
-            IFS=$func_to_host_pathlist_oldIFS
-            ;;
-        esac
-        if test -z "$func_to_host_pathlist_result" ; then
-          func_error "Could not determine the host path(s) corresponding to"
-          func_error "  '$1'"
-          func_error "Continuing, but uninstalled executables may not work."
-          # Fallback. This may break if $1 contains DOS-style drive
-          # specifications. The fix is not to complicate the expression
-          # below, but for the user to provide a working wine installation
-          # with winepath so that path translation in the cross-to-mingw
-          # case works properly.
-          lt_replace_pathsep_nix_to_dos="s|:|;|g"
-          func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\
-            $SED -e "$lt_replace_pathsep_nix_to_dos"`
-        fi
-        # Now, add the leading and trailing path separators back
-        case "$1" in
-          :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result"
-            ;;
-        esac
-        case "$1" in
-          *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;"
-            ;;
-        esac
-        ;;
-    esac
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
   fi
-}
-# end: func_to_host_pathlist
+fi\
+"
+}
+
 
 # func_emit_cwrapperexe_src
@@ -3142,11 +4148,10 @@
    This wrapper executable should never be moved out of the build directory.
    If it is, it will not operate correctly.
-
-   Currently, it simply execs the wrapper *script* "$SHELL $output",
-   but could eventually absorb all of the scripts functionality and
-   exec $objdir/$outputname directly.
 */
 EOF
 	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
 #include <stdio.h>
 #include <stdlib.h>
@@ -3155,5 +4160,4 @@
 # include <process.h>
 # include <io.h>
-# define setmode _setmode
 #else
 # include <unistd.h>
@@ -3161,10 +4165,4 @@
 # ifdef __CYGWIN__
 #  include <io.h>
-#  define HAVE_SETENV
-#  ifdef __STRICT_ANSI__
-char *realpath (const char *, char *);
-int putenv (char *);
-int setenv (const char *, const char *, int);
-#  endif
 # endif
 #endif
@@ -3178,4 +4176,42 @@
 #include <sys/stat.h>
 
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
 #if defined(PATH_MAX)
 # define LT_PATHMAX PATH_MAX
@@ -3193,12 +4229,5 @@
 #endif
 
-#ifdef _MSC_VER
-# define S_IXUSR _S_IEXEC
-# define stat _stat
-# ifndef _INTPTR_T_DEFINED
-#  define intptr_t int
-# endif
-#endif
-
+/* path handling portability macros */
 #ifndef DIR_SEPARATOR
 # define DIR_SEPARATOR '/'
@@ -3231,8 +4260,4 @@
 #endif /* PATH_SEPARATOR_2 */
 
-#ifdef __CYGWIN__
-# define FOPEN_WB "wb"
-#endif
-
 #ifndef FOPEN_WB
 # define FOPEN_WB "w"
@@ -3247,20 +4272,11 @@
 } while (0)
 
-#undef LTWRAPPER_DEBUGPRINTF
-#if defined DEBUGWRAPPER
-# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args
-static void
-ltwrapper_debugprintf (const char *fmt, ...)
-{
-    va_list args;
-    va_start (args, fmt);
-    (void) vfprintf (stderr, fmt, args);
-    va_end (args);
-}
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug = 1;
 #else
-# define LTWRAPPER_DEBUGPRINTF(args)
+static int lt_debug = 0;
 #endif
 
-const char *program_name = NULL;
+const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
 
 void *xmalloc (size_t num);
@@ -3272,39 +4288,25 @@
 int check_executable (const char *path);
 char *strendzap (char *str, const char *pat);
-void lt_fatal (const char *message, ...);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
 void lt_setenv (const char *name, const char *value);
 char *lt_extend_str (const char *orig_value, const char *add, int to_end);
-void lt_opt_process_env_set (const char *arg);
-void lt_opt_process_env_prepend (const char *arg);
-void lt_opt_process_env_append (const char *arg);
-int lt_split_name_value (const char *arg, char** name, char** value);
 void lt_update_exe_path (const char *name, const char *value);
 void lt_update_lib_path (const char *name, const char *value);
-
-static const char *script_text_part1 =
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
 EOF
 
-	    func_emit_wrapper_part1 yes |
-	        $SED -e 's/\([\\"]\)/\\\1/g' \
-	             -e 's/^/  "/' -e 's/$/\\n"/'
-	    echo ";"
 	    cat <<EOF
-
-static const char *script_text_part2 =
-EOF
-	    func_emit_wrapper_part2 yes |
-	        $SED -e 's/\([\\"]\)/\\\1/g' \
-	             -e 's/^/  "/' -e 's/$/\\n"/'
-	    echo ";"
-
-	    cat <<EOF
-const char * MAGIC_EXE = "$magic_exe";
+volatile const char * MAGIC_EXE = "$magic_exe";
 const char * LIB_PATH_VARNAME = "$shlibpath_var";
 EOF
 
 	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-              func_to_host_pathlist "$temp_rpath"
+              func_to_host_path "$temp_rpath"
 	      cat <<EOF
-const char * LIB_PATH_VALUE   = "$func_to_host_pathlist_result";
+const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
 EOF
 	    else
@@ -3315,8 +4317,8 @@
 
 	    if test -n "$dllsearchpath"; then
-              func_to_host_pathlist "$dllsearchpath:"
+              func_to_host_path "$dllsearchpath:"
 	      cat <<EOF
 const char * EXE_PATH_VARNAME = "PATH";
-const char * EXE_PATH_VALUE   = "$func_to_host_pathlist_result";
+const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
 EOF
 	    else
@@ -3341,22 +4343,8 @@
 
 #define LTWRAPPER_OPTION_PREFIX         "--lt-"
-#define LTWRAPPER_OPTION_PREFIX_LENGTH  5
-
-static const size_t opt_prefix_len         = LTWRAPPER_OPTION_PREFIX_LENGTH;
+
 static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
-
 static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
-
-static const size_t env_set_opt_len     = LTWRAPPER_OPTION_PREFIX_LENGTH + 7;
-static const char *env_set_opt          = LTWRAPPER_OPTION_PREFIX "env-set";
-  /* argument is putenv-style "foo=bar", value of foo is set to bar */
-
-static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11;
-static const char *env_prepend_opt      = LTWRAPPER_OPTION_PREFIX "env-prepend";
-  /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */
-
-static const size_t env_append_opt_len  = LTWRAPPER_OPTION_PREFIX_LENGTH + 10;
-static const char *env_append_opt       = LTWRAPPER_OPTION_PREFIX "env-append";
-  /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */
+static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
 
 int
@@ -3375,8 +4363,11 @@
 
   program_name = (char *) xstrdup (base_name (argv[0]));
-  LTWRAPPER_DEBUGPRINTF (("(main) argv[0]      : %s\n", argv[0]));
-  LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name));
-
-  /* very simple arg parsing; don't want to rely on getopt */
+  newargz = XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=0;
   for (i = 1; i < argc; i++)
     {
@@ -3392,23 +4383,55 @@
 
 	    cat <<"EOF"
-	  printf ("%s", script_text_part1);
-	  printf ("%s", script_text_part2);
+	  lt_dump_script (stdout);
 	  return 0;
 	}
+      if (strcmp (argv[i], debug_opt) == 0)
+	{
+          lt_debug = 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
     }
-
-  newargz = XMALLOC (char *, argc + 1);
+  newargz[++newargc] = NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
+
   tmp_pathspec = find_executable (argv[0]);
   if (tmp_pathspec == NULL)
-    lt_fatal ("Couldn't find %s", argv[0]);
-  LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n",
-			  tmp_pathspec));
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
 
   actual_cwrapper_path = chase_symlinks (tmp_pathspec);
-  LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n",
-			  actual_cwrapper_path));
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
   XFREE (tmp_pathspec);
 
-  actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path));
+  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
   strendzap (actual_cwrapper_path, actual_cwrapper_name);
 
@@ -3428,6 +4451,7 @@
   tmp_pathspec = 0;
 
-  LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n",
-			  target_name));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
 EOF
 
@@ -3479,78 +4503,17 @@
   lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
   lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
   lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
-  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
-
-  newargc=0;
-  for (i = 1; i < argc; i++)
-    {
-      if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0)
-        {
-          if (argv[i][env_set_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_set_opt_len + 1;
-              lt_opt_process_env_set (p);
-            }
-          else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_set (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_set_opt);
-          continue;
-        }
-      if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0)
-        {
-          if (argv[i][env_prepend_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_prepend_opt_len + 1;
-              lt_opt_process_env_prepend (p);
-            }
-          else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_prepend (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_prepend_opt);
-          continue;
-        }
-      if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0)
-        {
-          if (argv[i][env_append_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_append_opt_len + 1;
-              lt_opt_process_env_append (p);
-            }
-          else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_append (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_append_opt);
-          continue;
-        }
-      if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0)
-        {
-          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
-             namespace, but it is not one of the ones we know about and
-             have already dealt with, above (inluding dump-script), then
-             report an error. Otherwise, targets might begin to believe
-             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
-             namespace. The first time any user complains about this, we'll
-             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
-             or a configure.ac-settable value.
-           */
-          lt_fatal ("Unrecognized option in %s namespace: '%s'",
-                    ltwrapper_option_prefix, argv[i]);
-        }
-      /* otherwise ... */
-      newargz[++newargc] = xstrdup (argv[i]);
-    }
-  newargz[++newargc] = NULL;
-
-  LTWRAPPER_DEBUGPRINTF     (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>")));
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
   for (i = 0; i < newargc; i++)
     {
-      LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d]   : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>")));
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
     }
 
@@ -3561,9 +4524,12 @@
 		cat <<"EOF"
   /* execv doesn't actually work on mingw as expected on unix */
+  newargz = prepare_spawn (newargz);
   rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
   if (rval == -1)
     {
       /* failed to start process */
-      LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno));
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
       return 127;
     }
@@ -3587,5 +4553,5 @@
   void *p = (void *) malloc (num);
   if (!p)
-    lt_fatal ("Memory exhausted");
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
 
   return p;
@@ -3621,6 +4587,6 @@
   struct stat st;
 
-  LTWRAPPER_DEBUGPRINTF (("(check_executable)  : %s\n",
-			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
   if ((!path) || (!*path))
     return 0;
@@ -3639,6 +4605,6 @@
   struct stat st;
 
-  LTWRAPPER_DEBUGPRINTF (("(make_executable)   : %s\n",
-			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
   if ((!path) || (!*path))
     return 0;
@@ -3666,6 +4632,6 @@
   char *concat_name;
 
-  LTWRAPPER_DEBUGPRINTF (("(find_executable)   : %s\n",
-			  wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
 
   if ((wrapper == NULL) || (*wrapper == '\0'))
@@ -3720,5 +4686,6 @@
 		  /* empty path: current directory */
 		  if (getcwd (tmp, LT_PATHMAX) == NULL)
-		    lt_fatal ("getcwd failed");
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
 		  tmp_len = strlen (tmp);
 		  concat_name =
@@ -3745,5 +4712,6 @@
   /* Relative path | not found in path: prepend cwd */
   if (getcwd (tmp, LT_PATHMAX) == NULL)
-    lt_fatal ("getcwd failed");
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
   tmp_len = strlen (tmp);
   concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
@@ -3771,6 +4739,7 @@
   while (strlen (tmp_pathspec) && !has_symlinks)
     {
-      LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n",
-			      tmp_pathspec));
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
       if (lstat (tmp_pathspec, &s) == 0)
 	{
@@ -3794,6 +4763,7 @@
       else
 	{
-	  char *errstr = strerror (errno);
-	  lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr);
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
 	}
     }
@@ -3808,5 +4778,6 @@
   if (tmp_pathspec == 0)
     {
-      lt_fatal ("Could not follow symlinks for %s", pathspec);
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
     }
   return xstrdup (tmp_pathspec);
@@ -3834,9 +4805,23 @@
 }
 
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
 static void
-lt_error_core (int exit_status, const char *mode,
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
 	       const char *message, va_list ap)
 {
-  fprintf (stderr, "%s: %s: ", program_name, mode);
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
   vfprintf (stderr, message, ap);
   fprintf (stderr, ".\n");
@@ -3847,10 +4832,22 @@
 
 void
-lt_fatal (const char *message, ...)
+lt_fatal (const char *file, int line, const char *message, ...)
 {
   va_list ap;
   va_start (ap, message);
-  lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
   va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
 }
 
@@ -3858,7 +4855,7 @@
 lt_setenv (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
   {
 #ifdef HAVE_SETENV
@@ -3905,93 +4902,10 @@
 }
 
-int
-lt_split_name_value (const char *arg, char** name, char** value)
-{
-  const char *p;
-  int len;
-  if (!arg || !*arg)
-    return 1;
-
-  p = strchr (arg, (int)'=');
-
-  if (!p)
-    return 1;
-
-  *value = xstrdup (++p);
-
-  len = strlen (arg) - strlen (*value);
-  *name = XMALLOC (char, len);
-  strncpy (*name, arg, len-1);
-  (*name)[len - 1] = '\0';
-
-  return 0;
-}
-
-void
-lt_opt_process_env_set (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg);
-    }
-
-  lt_setenv (name, value);
-  XFREE (name);
-  XFREE (value);
-}
-
-void
-lt_opt_process_env_prepend (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-  char *new_value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg);
-    }
-
-  new_value = lt_extend_str (getenv (name), value, 0);
-  lt_setenv (name, new_value);
-  XFREE (new_value);
-  XFREE (name);
-  XFREE (value);
-}
-
-void
-lt_opt_process_env_append (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-  char *new_value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg);
-    }
-
-  new_value = lt_extend_str (getenv (name), value, 1);
-  lt_setenv (name, new_value);
-  XFREE (new_value);
-  XFREE (name);
-  XFREE (value);
-}
-
 void
 lt_update_exe_path (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
 
   if (name && *name && value && *value)
@@ -4012,7 +4926,7 @@
 lt_update_lib_path (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
 
   if (name && *name && value && *value)
@@ -4024,8 +4938,155 @@
 }
 
-
 EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and calls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >= 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc = 0; argv[argc] != NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv = XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i = 0; i < argc; i++)
+    {
+      const char *string = argv[i];
+
+      if (string[0] == '\0')
+	new_argv[i] = xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
+	{
+	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length = 0;
+	  backslashes = 0;
+	  if (quote_around)
+	    length++;
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		length += backslashes + 1;
+	      length++;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    length += backslashes + 1;
+
+	  quoted_string = XMALLOC (char, length + 1);
+
+	  p = quoted_string;
+	  backslashes = 0;
+	  if (quote_around)
+	    *p++ = '"';
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		{
+		  unsigned int j;
+		  for (j = backslashes + 1; j > 0; j--)
+		    *p++ = '\\';
+		}
+	      *p++ = c;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j = backslashes; j > 0; j--)
+		*p++ = '\\';
+	      *p++ = '"';
+	    }
+	  *p = '\0';
+
+	  new_argv[i] = quoted_string;
+	}
+      else
+	new_argv[i] = (char *) string;
+    }
+  new_argv[argc] = NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+	      $SED -n -e '
+s/^\(.\{79\}\)\(..*\)/\1\
+\2/
+h
+s/\([\\"]\)/\\\1/g
+s/$/\\n/
+s/\([^\n]*\).*/  fputs ("\1", f);/p
+g
+D'
+            cat <<"EOF"
+}
+EOF
 }
 # end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
+    esac
+}
 
 # func_mode_link arg...
@@ -4073,4 +5134,5 @@
 
     avoid_version=no
+    bindir=
     dlfiles=
     dlprefiles=
@@ -4165,4 +5227,9 @@
 
 	case $prev in
+	bindir)
+	  bindir="$arg"
+	  prev=
+	  continue
+	  ;;
 	dlfiles|dlprefiles)
 	  if test "$preload" = no; then
@@ -4196,7 +5263,7 @@
 	  *)
 	    if test "$prev" = dlfiles; then
-	      dlfiles="$dlfiles $arg"
+	      func_append dlfiles " $arg"
 	    else
-	      dlprefiles="$dlprefiles $arg"
+	      func_append dlprefiles " $arg"
 	    fi
 	    prev=
@@ -4222,5 +5289,5 @@
 	      case "$deplibs " in
 		*" $qarg.ltframework "*) ;;
-		*) deplibs="$deplibs $qarg.ltframework" # this is fixed later
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
 		   ;;
 	      esac
@@ -4241,5 +5308,5 @@
 	    for fil in `cat "$save_arg"`
 	    do
-#	      moreargs="$moreargs $fil"
+#	      func_append moreargs " $fil"
 	      arg=$fil
 	      # A libtool-controlled object.
@@ -4270,5 +5337,5 @@
 		  if test "$prev" = dlfiles; then
 		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		      dlfiles="$dlfiles $pic_object"
+		      func_append dlfiles " $pic_object"
 		      prev=
 		      continue
@@ -4282,5 +5349,5 @@
 		  if test "$prev" = dlprefiles; then
 		    # Preload the old-style object.
-		    dlprefiles="$dlprefiles $pic_object"
+		    func_append dlprefiles " $pic_object"
 		    prev=
 		  fi
@@ -4352,10 +5419,10 @@
 	    case "$rpath " in
 	    *" $arg "*) ;;
-	    *) rpath="$rpath $arg" ;;
+	    *) func_append rpath " $arg" ;;
 	    esac
 	  else
 	    case "$xrpath " in
 	    *" $arg "*) ;;
-	    *) xrpath="$xrpath $arg" ;;
+	    *) func_append xrpath " $arg" ;;
 	    esac
 	  fi
@@ -4369,11 +5436,11 @@
 	  ;;
 	weak)
-	  weak_libs="$weak_libs $arg"
+	  func_append weak_libs " $arg"
 	  prev=
 	  continue
 	  ;;
 	xcclinker)
-	  linker_flags="$linker_flags $qarg"
-	  compiler_flags="$compiler_flags $qarg"
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
 	  prev=
 	  func_append compile_command " $qarg"
@@ -4382,5 +5449,5 @@
 	  ;;
 	xcompiler)
-	  compiler_flags="$compiler_flags $qarg"
+	  func_append compiler_flags " $qarg"
 	  prev=
 	  func_append compile_command " $qarg"
@@ -4389,6 +5456,6 @@
 	  ;;
 	xlinker)
-	  linker_flags="$linker_flags $qarg"
-	  compiler_flags="$compiler_flags $wl$qarg"
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
 	  prev=
 	  func_append compile_command " $wl$qarg"
@@ -4426,4 +5493,9 @@
 	;;
 
+      -bindir)
+	prev=bindir
+	continue
+	;;
+
       -dlopen)
 	prev=dlfiles
@@ -4476,7 +5548,6 @@
 
       -L*)
-	func_stripname '-L' '' "$arg"
-	dir=$func_stripname_result
-	if test -z "$dir"; then
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
 	  if test "$#" -gt 0; then
 	    func_fatal_error "require no space between \`-L' and \`$1'"
@@ -4485,4 +5556,6 @@
 	  fi
 	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=$func_resolve_sysroot_result
 	# We need an absolute path.
 	case $dir in
@@ -4496,22 +5569,28 @@
 	esac
 	case "$deplibs " in
-	*" -L$dir "*) ;;
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
 	*)
-	  deplibs="$deplibs -L$dir"
-	  lib_search_path="$lib_search_path $dir"
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
 	  ;;
 	esac
 	case $host in
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-	  testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$dir:"*) ;;
 	  ::) dllsearchpath=$dir;;
-	  *) dllsearchpath="$dllsearchpath:$dir";;
+	  *) func_append dllsearchpath ":$dir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
 	  ::) dllsearchpath=$testbindir;;
-	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
@@ -4523,5 +5602,5 @@
 	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
 	    # These systems don't actually have a C or math library (as such)
 	    continue
@@ -4537,5 +5616,5 @@
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C and math libraries are in the System framework
-	    deplibs="$deplibs System.ltframework"
+	    func_append deplibs " System.ltframework"
 	    continue
 	    ;;
@@ -4557,5 +5636,5 @@
 	 esac
 	fi
-	deplibs="$deplibs $arg"
+	func_append deplibs " $arg"
 	continue
 	;;
@@ -4569,6 +5648,6 @@
       # classes, name mangling, and exception handling.
       # Darwin uses the -arch flag to determine output architecture.
-      -model|-arch|-isysroot)
-	compiler_flags="$compiler_flags $arg"
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
 	func_append compile_command " $arg"
 	func_append finalize_command " $arg"
@@ -4577,11 +5656,12 @@
 	;;
 
-      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
-	compiler_flags="$compiler_flags $arg"
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	func_append compiler_flags " $arg"
 	func_append compile_command " $arg"
 	func_append finalize_command " $arg"
 	case "$new_inherited_linker_flags " in
 	    *" $arg "*) ;;
-	    * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
 	esac
 	continue
@@ -4650,4 +5730,8 @@
 	case $dir in
 	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=*)
+	  func_stripname '=' '' "$dir"
+	  dir=$lt_sysroot$func_stripname_result
+	  ;;
 	*)
 	  func_fatal_error "only absolute run-paths are allowed"
@@ -4656,5 +5740,5 @@
 	case "$xrpath " in
 	*" $dir "*) ;;
-	*) xrpath="$xrpath $dir" ;;
+	*) func_append xrpath " $dir" ;;
 	esac
 	continue
@@ -4709,6 +5793,6 @@
 	  IFS="$save_ifs"
           func_quote_for_eval "$flag"
-	  arg="$arg $wl$func_quote_for_eval_result"
-	  compiler_flags="$compiler_flags $func_quote_for_eval_result"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
 	done
 	IFS="$save_ifs"
@@ -4725,7 +5809,7 @@
 	  IFS="$save_ifs"
           func_quote_for_eval "$flag"
-	  arg="$arg $wl$func_quote_for_eval_result"
-	  compiler_flags="$compiler_flags $wl$func_quote_for_eval_result"
-	  linker_flags="$linker_flags $func_quote_for_eval_result"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
 	done
 	IFS="$save_ifs"
@@ -4755,21 +5839,25 @@
 	;;
 
-      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
-      # -r[0-9][0-9]* specifies the processor on the SGI compiler
-      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
-      # +DA*, +DD* enable 64-bit mode on the HP compiler
-      # -q* pass through compiler args for the IBM compiler
-      # -m*, -t[45]*, -txscale* pass through architecture-specific
-      # compiler args for GCC
-      # -F/path gives path to uninstalled frameworks, gcc on darwin
-      # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC
-      # @file GCC response files
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=*                Portland pgcc target processor selection
+      # --sysroot=*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
       -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
-      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
         func_quote_for_eval "$arg"
 	arg="$func_quote_for_eval_result"
         func_append compile_command " $arg"
         func_append finalize_command " $arg"
-        compiler_flags="$compiler_flags $arg"
+        func_append compiler_flags " $arg"
         continue
         ;;
@@ -4783,5 +5871,5 @@
       *.$objext)
 	# A standard object.
-	objs="$objs $arg"
+	func_append objs " $arg"
 	;;
 
@@ -4814,5 +5902,5 @@
 	    if test "$prev" = dlfiles; then
 	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		dlfiles="$dlfiles $pic_object"
+		func_append dlfiles " $pic_object"
 		prev=
 		continue
@@ -4826,5 +5914,5 @@
 	    if test "$prev" = dlprefiles; then
 	      # Preload the old-style object.
-	      dlprefiles="$dlprefiles $pic_object"
+	      func_append dlprefiles " $pic_object"
 	      prev=
 	    fi
@@ -4871,6 +5959,6 @@
       *.$libext)
 	# An archive.
-	deplibs="$deplibs $arg"
-	old_deplibs="$old_deplibs $arg"
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
 	continue
 	;;
@@ -4879,14 +5967,15 @@
 	# A libtool-controlled library.
 
+	func_resolve_sysroot "$arg"
 	if test "$prev" = dlfiles; then
 	  # This library was specified with -dlopen.
-	  dlfiles="$dlfiles $arg"
+	  func_append dlfiles " $func_resolve_sysroot_result"
 	  prev=
 	elif test "$prev" = dlprefiles; then
 	  # The library was specified with -dlpreopen.
-	  dlprefiles="$dlprefiles $arg"
+	  func_append dlprefiles " $func_resolve_sysroot_result"
 	  prev=
 	else
-	  deplibs="$deplibs $arg"
+	  func_append deplibs " $func_resolve_sysroot_result"
 	fi
 	continue
@@ -4926,5 +6015,5 @@
     if test -n "$shlibpath_var"; then
       # get the directories listed in $shlibpath_var
-      eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
+      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
     else
       shlib_search_path=
@@ -4935,4 +6024,6 @@
     func_dirname "$output" "/" ""
     output_objdir="$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=$func_to_tool_file_result
     # Create the object directory.
     func_mkdir_p "$output_objdir"
@@ -4955,10 +6046,10 @@
     # that are linked more than once (e.g. -la -lb -la)
     for deplib in $deplibs; do
-      if $opt_duplicate_deps ; then
+      if $opt_preserve_dup_deps ; then
 	case "$libs " in
-	*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	esac
       fi
-      libs="$libs $deplib"
+      func_append libs " $deplib"
     done
 
@@ -4973,7 +6064,7 @@
 	for pre_post_dep in $predeps $postdeps; do
 	  case "$pre_post_deps " in
-	  *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
 	  esac
-	  pre_post_deps="$pre_post_deps $pre_post_dep"
+	  func_append pre_post_deps " $pre_post_dep"
 	done
       fi
@@ -5042,6 +6133,7 @@
 	  # Ignore non-libtool-libs
 	  dependency_libs=
+	  func_resolve_sysroot "$lib"
 	  case $lib in
-	  *.la)	func_source "$lib" ;;
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
 	  esac
 
@@ -5049,8 +6141,9 @@
 	  # has declared as weak libs
 	  for deplib in $dependency_libs; do
-            deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"`
+	    func_basename "$deplib"
+            deplib_base=$func_basename_result
 	    case " $weak_libs " in
 	    *" $deplib_base "*) ;;
-	    *) deplibs="$deplibs $deplib" ;;
+	    *) func_append deplibs " $deplib" ;;
 	    esac
 	  done
@@ -5068,14 +6161,15 @@
 	found=no
 	case $deplib in
-	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
 	  if test "$linkmode,$pass" = "prog,link"; then
 	    compile_deplibs="$deplib $compile_deplibs"
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
-	    compiler_flags="$compiler_flags $deplib"
+	    func_append compiler_flags " $deplib"
 	    if test "$linkmode" = lib ; then
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
-		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
 		esac
 	    fi
@@ -5162,5 +6256,5 @@
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
-		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
 		esac
 	    fi
@@ -5175,5 +6269,6 @@
 	    newdependency_libs="$deplib $newdependency_libs"
 	    func_stripname '-L' '' "$deplib"
-	    newlib_search_path="$newlib_search_path $func_stripname_result"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  prog)
@@ -5189,5 +6284,6 @@
 	    fi
 	    func_stripname '-L' '' "$deplib"
-	    newlib_search_path="$newlib_search_path $func_stripname_result"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  *)
@@ -5200,9 +6296,10 @@
 	  if test "$pass" = link; then
 	    func_stripname '-R' '' "$deplib"
-	    dir=$func_stripname_result
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=$func_resolve_sysroot_result
 	    # Make sure the xrpath contains only unique directories.
 	    case "$xrpath " in
 	    *" $dir "*) ;;
-	    *) xrpath="$xrpath $dir" ;;
+	    *) func_append xrpath " $dir" ;;
 	    esac
 	  fi
@@ -5210,5 +6307,8 @@
 	  continue
 	  ;;
-	*.la) lib="$deplib" ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=$func_resolve_sysroot_result
+	  ;;
 	*.$libext)
 	  if test "$pass" = conv; then
@@ -5228,5 +6328,5 @@
 		  set dummy $deplibs_check_method; shift
 		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
-		  if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
 		    | $EGREP "$match_pattern_regex" > /dev/null; then
 		    valid_a_lib=yes
@@ -5238,13 +6338,13 @@
 	      esac
 	      if test "$valid_a_lib" != yes; then
-		$ECHO
+		echo
 		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because the file extensions .$libext of this argument makes me believe"
-		$ECHO "*** that it is just a static archive that I should not use here."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me believe"
+		echo "*** that it is just a static archive that I should not use here."
 	      else
-		$ECHO
+		echo
 		$ECHO "*** Warning: Linking the shared library $output against the"
 		$ECHO "*** static library $deplib is not portable!"
@@ -5273,9 +6373,9 @@
 	      # If there is no dlopen support or we're linking statically,
 	      # we need to preload.
-	      newdlprefiles="$newdlprefiles $deplib"
+	      func_append newdlprefiles " $deplib"
 	      compile_deplibs="$deplib $compile_deplibs"
 	      finalize_deplibs="$deplib $finalize_deplibs"
 	    else
-	      newdlfiles="$newdlfiles $deplib"
+	      func_append newdlfiles " $deplib"
 	    fi
 	  fi
@@ -5319,18 +6419,18 @@
 	# Convert "-framework foo" to "foo.ltframework"
 	if test -n "$inherited_linker_flags"; then
-	  tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
 	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
 	    case " $new_inherited_linker_flags " in
 	      *" $tmp_inherited_linker_flag "*) ;;
-	      *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
 	    esac
 	  done
 	fi
-	dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	if test "$linkmode,$pass" = "lib,link" ||
 	   test "$linkmode,$pass" = "prog,scan" ||
 	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
-	  test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
-	  test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
 	fi
 
@@ -5343,6 +6443,6 @@
 	    fi
 	    # It is a libtool convenience library, so add in its objects.
-	    convenience="$convenience $ladir/$objdir/$old_library"
-	    old_convenience="$old_convenience $ladir/$objdir/$old_library"
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
 	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
 	    func_fatal_error "\`$lib' is not a convenience library"
@@ -5351,10 +6451,10 @@
 	  for deplib in $dependency_libs; do
 	    deplibs="$deplib $deplibs"
-	    if $opt_duplicate_deps ; then
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $deplib"
 	  done
 	  continue
@@ -5364,7 +6464,13 @@
 	# Get the name of the library we link against.
 	linklib=
-	for l in $old_library $library_names; do
-	  linklib="$l"
-	done
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" = yes ||
+	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	  linklib=$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib="$l"
+	  done
+	fi
 	if test -z "$linklib"; then
 	  func_fatal_error "cannot find name of link library for \`$lib'"
@@ -5383,7 +6489,7 @@
 	    # dependent libraries so libltdl's deplib preloader doesn't
 	    # bomb out in the load deplibs phase.
-	    dlprefiles="$dlprefiles $lib $dependency_libs"
+	    func_append dlprefiles " $lib $dependency_libs"
 	  else
-	    newdlfiles="$newdlfiles $lib"
+	    func_append newdlfiles " $lib"
 	  fi
 	  continue
@@ -5407,5 +6513,5 @@
 	# Find the relevant object directory and library name.
 	if test "X$installed" = Xyes; then
-	  if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
 	    func_warning "library \`$lib' was moved."
 	    dir="$ladir"
@@ -5413,6 +6519,6 @@
 	    libdir="$abs_ladir"
 	  else
-	    dir="$libdir"
-	    absdir="$libdir"
+	    dir="$lt_sysroot$libdir"
+	    absdir="$lt_sysroot$libdir"
 	  fi
 	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
@@ -5422,10 +6528,10 @@
 	    absdir="$abs_ladir"
 	    # Remove this search path later
-	    notinst_path="$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  else
 	    dir="$ladir/$objdir"
 	    absdir="$abs_ladir/$objdir"
 	    # Remove this search path later
-	    notinst_path="$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  fi
 	fi # $installed = yes
@@ -5438,18 +6544,44 @@
 	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
 	  fi
-	  # Prefer using a static library (so that no silly _DYNAMIC symbols
-	  # are required to link).
-	  if test -n "$old_library"; then
-	    newdlprefiles="$newdlprefiles $dir/$old_library"
-	    # Keep a list of preopened convenience libraries to check
-	    # that they are being used correctly in the link pass.
-	    test -z "$libdir" && \
-		dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library"
-	  # Otherwise, use the dlname, so that lt_dlopen finds it.
-	  elif test -n "$dlname"; then
-	    newdlprefiles="$newdlprefiles $dir/$dlname"
-	  else
-	    newdlprefiles="$newdlprefiles $dir/$linklib"
-	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
 	fi # $pass = dlpreopen
 
@@ -5469,5 +6601,5 @@
 
 	if test "$linkmode" = prog && test "$pass" != link; then
-	  newlib_search_path="$newlib_search_path $ladir"
+	  func_append newlib_search_path " $ladir"
 	  deplibs="$lib $deplibs"
 
@@ -5482,5 +6614,6 @@
 	    case $deplib in
 	    -L*) func_stripname '-L' '' "$deplib"
-	         newlib_search_path="$newlib_search_path $func_stripname_result"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
 		 ;;
 	    esac
@@ -5493,10 +6626,10 @@
 	      newdependency_libs="$deplib $newdependency_libs"
 	    fi
-	    if $opt_duplicate_deps ; then
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $deplib"
 	  done # for deplib
 	  continue
@@ -5513,5 +6646,5 @@
 	      case "$temp_rpath:" in
 	      *"$absdir:"*) ;;
-	      *) temp_rpath="$temp_rpath$absdir:" ;;
+	      *) func_append temp_rpath "$absdir:" ;;
 	      esac
 	    fi
@@ -5525,5 +6658,5 @@
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath="$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
@@ -5534,5 +6667,5 @@
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath="$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
@@ -5559,10 +6692,10 @@
 	  *cygwin* | *mingw* | *cegcc*)
 	      # No point in relinking DLLs because paths are not encoded
-	      notinst_deplibs="$notinst_deplibs $lib"
+	      func_append notinst_deplibs " $lib"
 	      need_relink=no
 	    ;;
 	  *)
 	    if test "$installed" = no; then
-	      notinst_deplibs="$notinst_deplibs $lib"
+	      func_append notinst_deplibs " $lib"
 	      need_relink=yes
 	    fi
@@ -5581,5 +6714,5 @@
 	  done
 	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
-	    $ECHO
+	    echo
 	    if test "$linkmode" = prog; then
 	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
@@ -5599,5 +6732,5 @@
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath="$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
@@ -5608,5 +6741,5 @@
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath="$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
@@ -5662,5 +6795,5 @@
 	  fi # test -n "$old_archive_from_expsyms_cmds"
 
-	  if test "$linkmode" = prog || test "$mode" != relink; then
+	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
 	    add_shlibpath=
 	    add_dir=
@@ -5684,7 +6817,7 @@
 			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
 			if test -z "$old_library" ; then
-			  $ECHO
-			  $ECHO "*** And there doesn't seem to be a static archive available"
-			  $ECHO "*** The link will probably fail, sorry"
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
 			else
 			  add="$dir/$old_library"
@@ -5713,10 +6846,10 @@
 		add="$dir/$linklib"
 	      elif test "$hardcode_minus_L" = yes; then
-		add_dir="-L$dir"
+		add_dir="-L$absdir"
 		# Try looking first in the location we're being installed to.
 		if test -n "$inst_prefix_dir"; then
 		  case $libdir in
 		    [\\/]*)
-		      add_dir="$add_dir -L$inst_prefix_dir$libdir"
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
 		      ;;
 		  esac
@@ -5740,5 +6873,5 @@
 	      case :$compile_shlibpath: in
 	      *":$add_shlibpath:"*) ;;
-	      *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
 	      esac
 	    fi
@@ -5754,5 +6887,5 @@
 		case :$finalize_shlibpath: in
 		*":$libdir:"*) ;;
-		*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
 		esac
 	      fi
@@ -5760,5 +6893,5 @@
 	  fi
 
-	  if test "$linkmode" = prog || test "$mode" = relink; then
+	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
 	    add_shlibpath=
 	    add_dir=
@@ -5774,5 +6907,5 @@
 	      case :$finalize_shlibpath: in
 	      *":$libdir:"*) ;;
-	      *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
 	      esac
 	      add="-l$name"
@@ -5791,5 +6924,5 @@
 		case $libdir in
 		  [\\/]*)
-		    add_dir="$add_dir -L$inst_prefix_dir$libdir"
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
 		    ;;
 		esac
@@ -5826,19 +6959,19 @@
 	    # Just print a warning and add the library to dependency_libs so
 	    # that the program can be linked against the static library.
-	    $ECHO
+	    echo
 	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
-	    $ECHO "*** I have the capability to make that library automatically link in when"
-	    $ECHO "*** you link to this library.  But I can only do this if you have a"
-	    $ECHO "*** shared version of the library, which you do not appear to have."
+	    echo "*** I have the capability to make that library automatically link in when"
+	    echo "*** you link to this library.  But I can only do this if you have a"
+	    echo "*** shared version of the library, which you do not appear to have."
 	    if test "$module" = yes; then
-	      $ECHO "*** But as you try to build a module library, libtool will still create "
-	      $ECHO "*** a static module, that should work as long as the dlopening application"
-	      $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime."
+	      echo "*** But as you try to build a module library, libtool will still create "
+	      echo "*** a static module, that should work as long as the dlopening application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
 	      if test -z "$global_symbol_pipe"; then
-		$ECHO
-		$ECHO "*** However, this would only work if libtool was able to extract symbol"
-		$ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
-		$ECHO "*** not find such a program.  So, this module is probably useless."
-		$ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
+		echo
+		echo "*** However, this would only work if libtool was able to extract symbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	      fi
 	      if test "$build_old_libs" = no; then
@@ -5868,7 +7001,7 @@
 		   case " $xrpath " in
 		   *" $temp_xrpath "*) ;;
-		   *) xrpath="$xrpath $temp_xrpath";;
+		   *) func_append xrpath " $temp_xrpath";;
 		   esac;;
-	      *) temp_deplibs="$temp_deplibs $libdir";;
+	      *) func_append temp_deplibs " $libdir";;
 	      esac
 	    done
@@ -5876,5 +7009,5 @@
 	  fi
 
-	  newlib_search_path="$newlib_search_path $absdir"
+	  func_append newlib_search_path " $absdir"
 	  # Link against this library
 	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
@@ -5883,10 +7016,16 @@
 	  for deplib in $dependency_libs; do
 	    newdependency_libs="$deplib $newdependency_libs"
-	    if $opt_duplicate_deps ; then
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $func_resolve_sysroot_result"
 	  done
 
@@ -5894,9 +7033,12 @@
 	    # Add the search paths of all dependency libraries
 	    for deplib in $dependency_libs; do
+	      path=
 	      case $deplib in
 	      -L*) path="$deplib" ;;
 	      *.la)
+	        func_resolve_sysroot "$deplib"
+	        deplib=$func_resolve_sysroot_result
 	        func_dirname "$deplib" "" "."
-		dir="$func_dirname_result"
+		dir=$func_dirname_result
 		# We need an absolute path.
 		case $dir in
@@ -5925,6 +7067,6 @@
                           darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
                       fi
-		      compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
-		      linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}"
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
 		      path=
 		    fi
@@ -5959,5 +7101,5 @@
 	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
 	else
-	  compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	fi
       fi
@@ -5976,5 +7118,5 @@
 	    case "$lib_search_path " in
 	    *" $dir "*) ;;
-	    *) lib_search_path="$lib_search_path $dir" ;;
+	    *) func_append lib_search_path " $dir" ;;
 	    esac
 	  done
@@ -6034,8 +7176,8 @@
 	      case " $tmp_libs " in
 	      *" $deplib "*) ;;
-	      *) tmp_libs="$tmp_libs $deplib" ;;
+	      *) func_append tmp_libs " $deplib" ;;
 	      esac
 	      ;;
-	    *) tmp_libs="$tmp_libs $deplib" ;;
+	    *) func_append tmp_libs " $deplib" ;;
 	    esac
 	  done
@@ -6053,5 +7195,5 @@
 	esac
 	if test -n "$i" ; then
-	  tmp_libs="$tmp_libs $i"
+	  func_append tmp_libs " $i"
 	fi
       done
@@ -6094,5 +7236,5 @@
       build_libtool_libs=no
       oldlibs="$output"
-      objs="$objs$old_deplibs"
+      func_append objs "$old_deplibs"
       ;;
 
@@ -6127,8 +7269,8 @@
 	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
 	else
-	  $ECHO
+	  echo
 	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
 	  $ECHO "*** objects $objs is not portable!"
-	  libobjs="$libobjs $objs"
+	  func_append libobjs " $objs"
 	fi
       fi
@@ -6189,4 +7331,5 @@
 	  #
 	  case $version_type in
+	  # correct linux to gnu/linux during the next big refactor
 	  darwin|linux|osf|windows|none)
 	    func_arith $number_major + $number_minor
@@ -6195,5 +7338,5 @@
 	    revision="$number_revision"
 	    ;;
-	  freebsd-aout|freebsd-elf|sunos)
+	  freebsd-aout|freebsd-elf|qnx|sunos)
 	    current="$number_major"
 	    revision="$number_minor"
@@ -6305,5 +7448,5 @@
 	  ;;
 
-	linux)
+	linux) # correct to gnu/linux during the next big refactor
 	  func_arith $current - $age
 	  major=.$func_arith_result
@@ -6328,5 +7471,5 @@
 
 	  # Make executables depend on our current version.
-	  verstring="$verstring:${current}.0"
+	  func_append verstring ":${current}.0"
 	  ;;
 
@@ -6396,8 +7539,8 @@
 
       func_generate_dlsyms "$libname" "$libname" "yes"
-      libobjs="$libobjs $symfileobj"
+      func_append libobjs " $symfileobj"
       test "X$libobjs" = "X " && libobjs=
 
-      if test "$mode" != relink; then
+      if test "$opt_mode" != relink; then
 	# Remove our outputs, but don't remove object files since they
 	# may have been created when compiling PIC objects.
@@ -6415,5 +7558,5 @@
 		 fi
 	       fi
-	       removelist="$removelist $p"
+	       func_append removelist " $p"
 	       ;;
 	    *) ;;
@@ -6426,15 +7569,15 @@
       # Now set the variables for building old libraries.
       if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
-	oldlibs="$oldlibs $output_objdir/$libname.$libext"
+	func_append oldlibs " $output_objdir/$libname.$libext"
 
 	# Transform .lo files to .o files.
-	oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
       fi
 
       # Eliminate all temporary directories.
       #for path in $notinst_path; do
-      #	lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"`
-      #	deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"`
-      #	dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"`
+      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
+      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
       #done
 
@@ -6443,8 +7586,9 @@
 	temp_xrpath=
 	for libdir in $xrpath; do
-	  temp_xrpath="$temp_xrpath -R$libdir"
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath="$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
@@ -6460,5 +7604,5 @@
 	case " $dlprefiles $dlfiles " in
 	*" $lib "*) ;;
-	*) dlfiles="$dlfiles $lib" ;;
+	*) func_append dlfiles " $lib" ;;
 	esac
       done
@@ -6470,5 +7614,5 @@
 	case "$dlprefiles " in
 	*" $lib "*) ;;
-	*) dlprefiles="$dlprefiles $lib" ;;
+	*) func_append dlprefiles " $lib" ;;
 	esac
       done
@@ -6477,10 +7621,10 @@
 	if test -n "$rpath"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
 	    # these systems don't actually have a c library (as such)!
 	    ;;
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C library is in the System framework
-	    deplibs="$deplibs System.ltframework"
+	    func_append deplibs " System.ltframework"
 	    ;;
 	  *-*-netbsd*)
@@ -6499,5 +7643,5 @@
 	    # Add libc to deplibs on all other systems if necessary.
 	    if test "$build_libtool_need_lc" = "yes"; then
-	      deplibs="$deplibs -lc"
+	      func_append deplibs " -lc"
 	    fi
 	    ;;
@@ -6548,5 +7692,5 @@
 		  case " $predeps $postdeps " in
 		  *" $i "*)
-		    newdeplibs="$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		    i=""
 		    ;;
@@ -6559,19 +7703,19 @@
 		  deplib_match=$1
 		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		    newdeplibs="$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		  else
 		    droppeddeps=yes
-		    $ECHO
+		    echo
 		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		    $ECHO "*** I have the capability to make that library automatically link in when"
-		    $ECHO "*** you link to this library.  But I can only do this if you have a"
-		    $ECHO "*** shared version of the library, which I believe you do not have"
-		    $ECHO "*** because a test_compile did reveal that the linker did not use it for"
-		    $ECHO "*** its dynamic dependency list that programs get resolved with at runtime."
+		    echo "*** I have the capability to make that library automatically link in when"
+		    echo "*** you link to this library.  But I can only do this if you have a"
+		    echo "*** shared version of the library, which I believe you do not have"
+		    echo "*** because a test_compile did reveal that the linker did not use it for"
+		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
 		  fi
 		fi
 		;;
 	      *)
-		newdeplibs="$newdeplibs $i"
+		func_append newdeplibs " $i"
 		;;
 	      esac
@@ -6591,5 +7735,5 @@
 		    case " $predeps $postdeps " in
 		    *" $i "*)
-		      newdeplibs="$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		      i=""
 		      ;;
@@ -6602,27 +7746,27 @@
 		    deplib_match=$1
 		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		      newdeplibs="$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		    else
 		      droppeddeps=yes
-		      $ECHO
+		      echo
 		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		      $ECHO "*** I have the capability to make that library automatically link in when"
-		      $ECHO "*** you link to this library.  But I can only do this if you have a"
-		      $ECHO "*** shared version of the library, which you do not appear to have"
-		      $ECHO "*** because a test_compile did reveal that the linker did not use this one"
-		      $ECHO "*** as a dynamic dependency that programs can get resolved with at runtime."
+		      echo "*** I have the capability to make that library automatically link in when"
+		      echo "*** you link to this library.  But I can only do this if you have a"
+		      echo "*** shared version of the library, which you do not appear to have"
+		      echo "*** because a test_compile did reveal that the linker did not use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
 		    fi
 		  fi
 		else
 		  droppeddeps=yes
-		  $ECHO
+		  echo
 		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
-		  $ECHO "*** make it link in!  You will probably need to install it or some"
-		  $ECHO "*** library that it depends on before this library will be fully"
-		  $ECHO "*** functional.  Installing it before continuing would be even better."
+		  echo "*** make it link in!  You will probably need to install it or some"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even better."
 		fi
 		;;
 	      *)
-		newdeplibs="$newdeplibs $i"
+		func_append newdeplibs " $i"
 		;;
 	      esac
@@ -6641,5 +7785,5 @@
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs="$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=""
 		  ;;
@@ -6648,6 +7792,18 @@
 	      if test -n "$a_deplib" ; then
 		libname=`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=$libname
+		fi
+		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+		  if test "$want_nocaseglob" = yes; then
+		    shopt -s nocaseglob
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
 		  for potent_lib in $potential_libs; do
 		      # Follow soft links.
@@ -6666,5 +7822,5 @@
 			case $potliblink in
 			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
-			*) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
 			esac
 		      done
@@ -6672,5 +7828,5 @@
 			 $SED -e 10q |
 			 $EGREP "$file_magic_regex" > /dev/null; then
-			newdeplibs="$newdeplibs $a_deplib"
+			func_append newdeplibs " $a_deplib"
 			a_deplib=""
 			break 2
@@ -6681,10 +7837,10 @@
 	      if test -n "$a_deplib" ; then
 		droppeddeps=yes
-		$ECHO
+		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because I did check the linker path looking for a file starting"
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
 		if test -z "$potlib" ; then
 		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
@@ -6697,5 +7853,5 @@
 	    *)
 	      # Add a -L argument.
-	      newdeplibs="$newdeplibs $a_deplib"
+	      func_append newdeplibs " $a_deplib"
 	      ;;
 	    esac
@@ -6713,5 +7869,5 @@
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs="$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=""
 		  ;;
@@ -6724,7 +7880,7 @@
 		  for potent_lib in $potential_libs; do
 		    potlib="$potent_lib" # see symlink-check above in file_magic test
-		    if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
 		       $EGREP "$match_pattern_regex" > /dev/null; then
-		      newdeplibs="$newdeplibs $a_deplib"
+		      func_append newdeplibs " $a_deplib"
 		      a_deplib=""
 		      break 2
@@ -6735,10 +7891,10 @@
 	      if test -n "$a_deplib" ; then
 		droppeddeps=yes
-		$ECHO
+		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because I did check the linker path looking for a file starting"
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
 		if test -z "$potlib" ; then
 		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
@@ -6751,5 +7907,5 @@
 	    *)
 	      # Add a -L argument.
-	      newdeplibs="$newdeplibs $a_deplib"
+	      func_append newdeplibs " $a_deplib"
 	      ;;
 	    esac
@@ -6758,23 +7914,23 @@
 	none | unknown | *)
 	  newdeplibs=""
-	  tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \
-	      -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'`
+	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
 	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
 	    for i in $predeps $postdeps ; do
 	      # can't use Xsed below, because $i might contain '/'
-	      tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"`
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
 	    done
 	  fi
-	  if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[	 ]//g' |
-	     $GREP . >/dev/null; then
-	    $ECHO
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
 	    if test "X$deplibs_check_method" = "Xnone"; then
-	      $ECHO "*** Warning: inter-library dependencies are not supported in this platform."
+	      echo "*** Warning: inter-library dependencies are not supported in this platform."
 	    else
-	      $ECHO "*** Warning: inter-library dependencies are not known to be supported."
+	      echo "*** Warning: inter-library dependencies are not known to be supported."
 	    fi
-	    $ECHO "*** All declared inter-library dependencies are being dropped."
+	    echo "*** All declared inter-library dependencies are being dropped."
 	    droppeddeps=yes
-	  fi
+	    ;;
+	  esac
 	  ;;
 	esac
@@ -6788,5 +7944,5 @@
 	*-*-rhapsody* | *-*-darwin1.[012])
 	  # On Rhapsody replace the C library with the System framework
-	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
 	  ;;
 	esac
@@ -6794,15 +7950,15 @@
 	if test "$droppeddeps" = yes; then
 	  if test "$module" = yes; then
-	    $ECHO
-	    $ECHO "*** Warning: libtool could not satisfy all declared inter-library"
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-library"
 	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
-	    $ECHO "*** a static module, that should work as long as the dlopening"
-	    $ECHO "*** application is linked with the -dlopen flag."
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
 	    if test -z "$global_symbol_pipe"; then
-	      $ECHO
-	      $ECHO "*** However, this would only work if libtool was able to extract symbol"
-	      $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
-	      $ECHO "*** not find such a program.  So, this module is probably useless."
-	      $ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
+	      echo
+	      echo "*** However, this would only work if libtool was able to extract symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** not find such a program.  So, this module is probably useless."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	    fi
 	    if test "$build_old_libs" = no; then
@@ -6814,14 +7970,14 @@
 	    fi
 	  else
-	    $ECHO "*** The inter-library dependencies that have been dropped here will be"
-	    $ECHO "*** automatically added whenever a program is linked with this library"
-	    $ECHO "*** or is declared to -dlopen it."
+	    echo "*** The inter-library dependencies that have been dropped here will be"
+	    echo "*** automatically added whenever a program is linked with this library"
+	    echo "*** or is declared to -dlopen it."
 
 	    if test "$allow_undefined" = no; then
-	      $ECHO
-	      $ECHO "*** Since this library must not contain undefined symbols,"
-	      $ECHO "*** because either the platform does not support them or"
-	      $ECHO "*** it was explicitly requested with -no-undefined,"
-	      $ECHO "*** libtool will only create a static version of it."
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
 	      if test "$build_old_libs" = no; then
 		oldlibs="$output_objdir/$libname.$libext"
@@ -6840,7 +7996,7 @@
       case $host in
 	*-*-darwin*)
-	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	  ;;
       esac
@@ -6855,5 +8011,5 @@
 	  case " $deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs="$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
@@ -6865,8 +8021,8 @@
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs="$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs="$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
@@ -6880,4 +8036,9 @@
       # Test again, we may have decided not to build it any more
       if test "$build_libtool_libs" = yes; then
+	# Remove ${wl} instances when linking with ld.
+	# FIXME: should test the right _cmds variable.
+	case $archive_cmds in
+	  *\$LD\ *) wl= ;;
+        esac
 	if test "$hardcode_into_libs" = yes; then
 	  # Hardcode the library paths
@@ -6885,8 +8046,10 @@
 	  dep_rpath=
 	  rpath="$finalize_rpath"
-	  test "$mode" != relink && rpath="$compile_rpath$rpath"
+	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
 	  for libdir in $rpath; do
 	    if test -n "$hardcode_libdir_flag_spec"; then
 	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=$func_replace_sysroot_result
 		if test -z "$hardcode_libdirs"; then
 		  hardcode_libdirs="$libdir"
@@ -6897,5 +8060,5 @@
 		    ;;
 		  *)
-		    hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		    ;;
 		  esac
@@ -6903,10 +8066,10 @@
 	      else
 		eval flag=\"$hardcode_libdir_flag_spec\"
-		dep_rpath="$dep_rpath $flag"
+		func_append dep_rpath " $flag"
 	      fi
 	    elif test -n "$runpath_var"; then
 	      case "$perm_rpath " in
 	      *" $libdir "*) ;;
-	      *) perm_rpath="$perm_rpath $libdir" ;;
+	      *) func_append perm_rpath " $libdir" ;;
 	      esac
 	    fi
@@ -6916,9 +8079,5 @@
 	     test -n "$hardcode_libdirs"; then
 	    libdir="$hardcode_libdirs"
-	    if test -n "$hardcode_libdir_flag_spec_ld"; then
-	      eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
-	    else
-	      eval dep_rpath=\"$hardcode_libdir_flag_spec\"
-	    fi
+	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
 	  fi
 	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
@@ -6926,5 +8085,5 @@
 	    rpath=
 	    for dir in $perm_rpath; do
-	      rpath="$rpath$dir:"
+	      func_append rpath "$dir:"
 	    done
 	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
@@ -6934,5 +8093,5 @@
 
 	shlibpath="$finalize_shlibpath"
-	test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
 	if test -n "$shlibpath"; then
 	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
@@ -6960,9 +8119,9 @@
 	for link
 	do
-	  linknames="$linknames $link"
+	  func_append linknames " $link"
 	done
 
 	# Use standard objects if they are pic
-	test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	test "X$libobjs" = "X " && libobjs=
 
@@ -6971,5 +8130,5 @@
 	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
 	  export_symbols="$output_objdir/$libname.uexp"
-	  delfiles="$delfiles $export_symbols"
+	  func_append delfiles " $export_symbols"
 	fi
 
@@ -7002,11 +8161,43 @@
 	    cmds=$export_symbols_cmds
 	    save_ifs="$IFS"; IFS='~'
-	    for cmd in $cmds; do
+	    for cmd1 in $cmds; do
 	      IFS="$save_ifs"
-	      eval cmd=\"$cmd\"
-	      func_len " $cmd"
-	      len=$func_len_result
-	      if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=yes
+		  eval cmd=\"$cmd1\"
+		  func_len " $cmd"
+		  len=$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=no
+		  ;;
+	      esac
+	      if test "$try_normal_branch" = yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
 		func_show_eval "$cmd" 'exit $?'
+		skipped_export=false
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=$func_basename_result
+		save_libobjs=$libobjs
+		save_output=$output
+		output=${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=$save_output
+		libobjs=$save_libobjs
 		skipped_export=false
 	      else
@@ -7030,5 +8221,5 @@
 	  tmp_export_symbols="$export_symbols"
 	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	  $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	fi
 
@@ -7042,5 +8233,5 @@
 	  # isn't a blessed tool.
 	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	  delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
 	  export_symbols=$output_objdir/$libname.def
 	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
@@ -7052,5 +8243,5 @@
 	  *" $test_deplib "*) ;;
 	  *)
-	    tmp_deplibs="$tmp_deplibs $test_deplib"
+	    func_append tmp_deplibs " $test_deplib"
 	    ;;
 	  esac
@@ -7072,8 +8263,8 @@
 	  else
 	    gentop="$output_objdir/${outputname}x"
-	    generated="$generated $gentop"
+	    func_append generated " $gentop"
 
 	    func_extract_archives $gentop $convenience
-	    libobjs="$libobjs $func_extract_archives_result"
+	    func_append libobjs " $func_extract_archives_result"
 	    test "X$libobjs" = "X " && libobjs=
 	  fi
@@ -7082,9 +8273,9 @@
 	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
 	  eval flag=\"$thread_safe_flag_spec\"
-	  linker_flags="$linker_flags $flag"
+	  func_append linker_flags " $flag"
 	fi
 
 	# Make a backup of the uninstalled library when relinking
-	if test "$mode" = relink; then
+	if test "$opt_mode" = relink; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
 	fi
@@ -7131,5 +8322,6 @@
 	  fi
 	  save_output=$output
-	  output_la=`$ECHO "X$output" | $Xsed -e "$basename"`
+	  func_basename "$output"
+	  output_la=$func_basename_result
 
 	  # Clear the reloadable object creation command queue and
@@ -7144,11 +8336,14 @@
 	    output=${output_objdir}/${output_la}.lnkscript
 	    func_verbose "creating GNU ld script: $output"
-	    $ECHO 'INPUT (' > $output
+	    echo 'INPUT (' > $output
 	    for obj in $save_libobjs
 	    do
-	      $ECHO "$obj" >> $output
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
 	    done
-	    $ECHO ')' >> $output
-	    delfiles="$delfiles $output"
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$func_to_tool_file_result
 	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
 	    output=${output_objdir}/${output_la}.lnk
@@ -7164,8 +8359,10 @@
 	    for obj
 	    do
-	      $ECHO "$obj" >> $output
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
 	    done
-	    delfiles="$delfiles $output"
-	    output=$firstobj\"$file_list_spec$output\"
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
 	  else
 	    if test -n "$save_libobjs"; then
@@ -7191,9 +8388,11 @@
 		  if test "$k" -eq 1 ; then
 		    # The first file doesn't have a previous command to add.
-		    eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+		    reload_objs=$objlist
+		    eval concat_cmds=\"$reload_cmds\"
 		  else
 		    # All subsequent reloadable object files will link in
 		    # the last one created.
-		    eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\"
+		    reload_objs="$objlist $last_robj"
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
 		  fi
 		  last_robj=$output_objdir/$output_la-${k}.$objext
@@ -7201,5 +8400,5 @@
 		  k=$func_arith_result
 		  output=$output_objdir/$output_la-${k}.$objext
-		  objlist=$obj
+		  objlist=" $obj"
 		  func_len " $last_robj"
 		  func_arith $len0 + $func_len_result
@@ -7211,9 +8410,10 @@
 	      # files will link in the last one created.
 	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+	      reload_objs="$objlist $last_robj"
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
 	      if test -n "$last_robj"; then
 	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
 	      fi
-	      delfiles="$delfiles $output"
+	      func_append delfiles " $output"
 
 	    else
@@ -7249,5 +8449,5 @@
 
 		# Restore the uninstalled library and exit
-		if test "$mode" = relink; then
+		if test "$opt_mode" = relink; then
 		  ( cd "$output_objdir" && \
 		    $RM "${realname}T" && \
@@ -7270,5 +8470,5 @@
 	      tmp_export_symbols="$export_symbols"
 	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	      $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	    fi
 
@@ -7282,5 +8482,5 @@
 	      # isn't a blessed tool.
 	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	      delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
 	      export_symbols=$output_objdir/$libname.def
 	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
@@ -7323,8 +8523,8 @@
 	if test -n "$dlprefiles"; then
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
-	  libobjs="$libobjs $func_extract_archives_result"
+	  func_append libobjs " $func_extract_archives_result"
 	  test "X$libobjs" = "X " && libobjs=
 	fi
@@ -7342,5 +8542,5 @@
 
 	    # Restore the uninstalled library and exit
-	    if test "$mode" = relink; then
+	    if test "$opt_mode" = relink; then
 	      ( cd "$output_objdir" && \
 	        $RM "${realname}T" && \
@@ -7354,5 +8554,5 @@
 
 	# Restore the uninstalled library and exit
-	if test "$mode" = relink; then
+	if test "$opt_mode" = relink; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
 
@@ -7435,8 +8635,8 @@
 	if test -n "$whole_archive_flag_spec"; then
 	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
-	  reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
+	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
 	else
 	  gentop="$output_objdir/${obj}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $convenience
@@ -7445,6 +8645,9 @@
       fi
 
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+
       # Create the old-style object.
-      reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
 
       output="$obj"
@@ -7506,6 +8709,6 @@
       *-*-rhapsody* | *-*-darwin1.[012])
 	# On Rhapsody replace the C library is the System framework
-	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
-	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
 	;;
       esac
@@ -7518,12 +8721,12 @@
 	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
 	    10.[0123])
-	      compile_command="$compile_command ${wl}-bind_at_load"
-	      finalize_command="$finalize_command ${wl}-bind_at_load"
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
 	    ;;
 	  esac
 	fi
 	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
-	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	;;
       esac
@@ -7539,5 +8742,5 @@
 	  case " $compile_deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs="$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
@@ -7549,8 +8752,8 @@
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs="$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs="$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
@@ -7558,6 +8761,6 @@
 
 
-      compile_command="$compile_command $compile_deplibs"
-      finalize_command="$finalize_command $finalize_deplibs"
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
 
       if test -n "$rpath$xrpath"; then
@@ -7567,5 +8770,5 @@
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath="$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
@@ -7586,5 +8789,5 @@
 		;;
 	      *)
-		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
@@ -7592,10 +8795,10 @@
 	  else
 	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    rpath="$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) perm_rpath="$perm_rpath $libdir" ;;
+	  *) func_append perm_rpath " $libdir" ;;
 	  esac
 	fi
@@ -7606,10 +8809,10 @@
 	  *":$libdir:"*) ;;
 	  ::) dllsearchpath=$libdir;;
-	  *) dllsearchpath="$dllsearchpath:$libdir";;
+	  *) func_append dllsearchpath ":$libdir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
 	  ::) dllsearchpath=$testbindir;;
-	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
@@ -7637,5 +8840,5 @@
 		;;
 	      *)
-		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
@@ -7643,10 +8846,10 @@
 	  else
 	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    rpath="$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$finalize_perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
 	  esac
 	fi
@@ -7662,6 +8865,6 @@
       if test -n "$libobjs" && test "$build_old_libs" = yes; then
 	# Transform all the library objects into standard objects.
-	compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
-	finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
       fi
 
@@ -7675,12 +8878,12 @@
       wrappers_required=yes
       case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
       *cygwin* | *mingw* )
         if test "$build_libtool_libs" != yes; then
           wrappers_required=no
         fi
-        ;;
-      *cegcc)
-        # Disable wrappers for cegcc, we are cross compiling anyway.
-        wrappers_required=no
         ;;
       *)
@@ -7692,5 +8895,5 @@
       if test "$wrappers_required" = no; then
 	# Replace the output file specification.
-	compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	link_command="$compile_command$compile_rpath"
 
@@ -7698,4 +8901,10 @@
 	exit_status=0
 	func_show_eval "$link_command" 'exit_status=$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
 
 	# Delete the generated files.
@@ -7721,5 +8930,5 @@
 	  rpath=
 	  for dir in $perm_rpath; do
-	    rpath="$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
@@ -7729,5 +8938,5 @@
 	  rpath=
 	  for dir in $finalize_perm_rpath; do
-	    rpath="$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
@@ -7739,9 +8948,16 @@
 	link_command="$compile_var$compile_command$compile_rpath"
 	# Replace the output file specification.
-	link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	# Delete the old output file.
 	$opt_dry_run || $RM $output
 	# Link the executable and exit
 	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
 	exit $EXIT_SUCCESS
       fi
@@ -7758,5 +8974,5 @@
 	  link_command="$finalize_var$compile_command$finalize_rpath"
 	  if test "$fast_install" = yes; then
-	    relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'`
+	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
 	  else
 	    # fast_install is set to needless
@@ -7770,5 +8986,5 @@
 
       # Replace the output file specification.
-      link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
 
       # Delete the old output files.
@@ -7776,4 +8992,10 @@
 
       func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
 
       # Now create the wrapper script.
@@ -7794,16 +9016,5 @@
 	done
 	relink_command="(cd `pwd`; $relink_command)"
-	relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
-      fi
-
-      # Quote $ECHO for shipping.
-      if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then
-	case $progpath in
-	[\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
-	*) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
-	esac
-	qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"`
-      else
-	qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"`
+	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       fi
 
@@ -7885,5 +9096,5 @@
 	  oldobjs="$old_deplibs $non_pic_objects"
 	  if test "$preload" = yes && test -f "$symfileobj"; then
-	    oldobjs="$oldobjs $symfileobj"
+	    func_append oldobjs " $symfileobj"
 	  fi
 	fi
@@ -7893,8 +9104,8 @@
       if test -n "$addlibs"; then
 	gentop="$output_objdir/${outputname}x"
-	generated="$generated $gentop"
+	func_append generated " $gentop"
 
 	func_extract_archives $gentop $addlibs
-	oldobjs="$oldobjs $func_extract_archives_result"
+	func_append oldobjs " $func_extract_archives_result"
       fi
 
@@ -7907,8 +9118,8 @@
 	if test -n "$dlprefiles"; then
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
-	  oldobjs="$oldobjs $func_extract_archives_result"
+	  func_append oldobjs " $func_extract_archives_result"
 	fi
 
@@ -7926,7 +9137,7 @@
 	  :
 	else
-	  $ECHO "copying selected object files to avoid basename conflicts..."
+	  echo "copying selected object files to avoid basename conflicts..."
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 	  func_mkdir_p "$gentop"
 	  save_oldobjs=$oldobjs
@@ -7952,10 +9163,12 @@
 	      done
 	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
-	      oldobjs="$oldobjs $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
 	      ;;
-	    *) oldobjs="$oldobjs $obj" ;;
+	    *) func_append oldobjs " $obj" ;;
 	    esac
 	  done
 	fi
+	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+	tool_oldlib=$func_to_tool_file_result
 	eval cmds=\"$old_archive_cmds\"
 
@@ -7963,4 +9176,14 @@
 	len=$func_len_result
 	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
 	  cmds=$old_archive_cmds
 	else
@@ -8037,5 +9260,5 @@
       # Quote the link command for shipping.
       relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
-      relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       if test "$hardcode_automatic" = yes ; then
 	relink_command=
@@ -8057,10 +9280,21 @@
 		func_basename "$deplib"
 		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		func_resolve_sysroot "$deplib"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
 		test -z "$libdir" && \
 		  func_fatal_error "\`$deplib' is not a valid libtool archive"
-		newdependency_libs="$newdependency_libs $libdir/$name"
+		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
 		;;
-	      *) newdependency_libs="$newdependency_libs $deplib" ;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
 	      esac
 	    done
@@ -8076,7 +9310,7 @@
 		test -z "$libdir" && \
 		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		newdlfiles="$newdlfiles $libdir/$name"
+		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
-	      *) newdlfiles="$newdlfiles $lib" ;;
+	      *) func_append newdlfiles " $lib" ;;
 	      esac
 	    done
@@ -8095,5 +9329,5 @@
 		test -z "$libdir" && \
 		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		newdlprefiles="$newdlprefiles $libdir/$name"
+		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
 	      esac
@@ -8107,5 +9341,5 @@
 		*) abs=`pwd`"/$lib" ;;
 	      esac
-	      newdlfiles="$newdlfiles $abs"
+	      func_append newdlfiles " $abs"
 	    done
 	    dlfiles="$newdlfiles"
@@ -8116,5 +9350,5 @@
 		*) abs=`pwd`"/$lib" ;;
 	      esac
-	      newdlprefiles="$newdlprefiles $abs"
+	      func_append newdlprefiles " $abs"
 	    done
 	    dlprefiles="$newdlprefiles"
@@ -8122,7 +9356,25 @@
 	  $RM $output
 	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
 	  tdlname=$dlname
 	  case $host,$output,$installed,$module,$dlname in
-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" != x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=../bin/$dlname
+	      fi
+	      ;;
 	  esac
 	  $ECHO > $output "\
@@ -8183,5 +9435,5 @@
 }
 
-{ test "$mode" = link || test "$mode" = relink; } &&
+{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
     func_mode_link ${1+"$@"}
 
@@ -8203,7 +9455,7 @@
     do
       case $arg in
-      -f) RM="$RM $arg"; rmforce=yes ;;
-      -*) RM="$RM $arg" ;;
-      *) files="$files $arg" ;;
+      -f) func_append RM " $arg"; rmforce=yes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
       esac
     done
@@ -8214,22 +9466,21 @@
     rmdirs=
 
-    origobjdir="$objdir"
     for file in $files; do
       func_dirname "$file" "" "."
       dir="$func_dirname_result"
       if test "X$dir" = X.; then
-	objdir="$origobjdir"
+	odir="$objdir"
       else
-	objdir="$dir/$origobjdir"
+	odir="$dir/$objdir"
       fi
       func_basename "$file"
       name="$func_basename_result"
-      test "$mode" = uninstall && objdir="$dir"
-
-      # Remember objdir for removal later, being careful to avoid duplicates
-      if test "$mode" = clean; then
+      test "$opt_mode" = uninstall && odir="$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" = clean; then
 	case " $rmdirs " in
-	  *" $objdir "*) ;;
-	  *) rmdirs="$rmdirs $objdir" ;;
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
 	esac
       fi
@@ -8257,16 +9508,15 @@
 	  # Delete the libtool libraries and symlinks.
 	  for n in $library_names; do
-	    rmfiles="$rmfiles $objdir/$n"
+	    func_append rmfiles " $odir/$n"
 	  done
-	  test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
-
-	  case "$mode" in
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
 	  clean)
-	    case "  $library_names " in
-	    # "  " in the beginning catches empty $dlname
+	    case " $library_names " in
 	    *" $dlname "*) ;;
-	    *) rmfiles="$rmfiles $objdir/$dlname" ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
 	    esac
-	    test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
 	    ;;
 	  uninstall)
@@ -8296,5 +9546,5 @@
 	  if test -n "$pic_object" &&
 	     test "$pic_object" != none; then
-	    rmfiles="$rmfiles $dir/$pic_object"
+	    func_append rmfiles " $dir/$pic_object"
 	  fi
 
@@ -8302,5 +9552,5 @@
 	  if test -n "$non_pic_object" &&
 	     test "$non_pic_object" != none; then
-	    rmfiles="$rmfiles $dir/$non_pic_object"
+	    func_append rmfiles " $dir/$non_pic_object"
 	  fi
 	fi
@@ -8308,5 +9558,5 @@
 
       *)
-	if test "$mode" = clean ; then
+	if test "$opt_mode" = clean ; then
 	  noexename=$name
 	  case $file in
@@ -8318,5 +9568,5 @@
 	    # $file with .exe has already been added to rmfiles,
 	    # add $file without .exe
-	    rmfiles="$rmfiles $file"
+	    func_append rmfiles " $file"
 	    ;;
 	  esac
@@ -8327,5 +9577,5 @@
 	      relink_command=
 	      func_source $func_ltwrapper_scriptname_result
-	      rmfiles="$rmfiles $func_ltwrapper_scriptname_result"
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
 	    else
 	      relink_command=
@@ -8335,10 +9585,10 @@
 	    # note $name still contains .exe if it was in $file originally
 	    # as does the version of $file that was added into $rmfiles
-	    rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
 	    if test "$fast_install" = yes && test -n "$relink_command"; then
-	      rmfiles="$rmfiles $objdir/lt-$name"
+	      func_append rmfiles " $odir/lt-$name"
 	    fi
 	    if test "X$noexename" != "X$name" ; then
-	      rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+	      func_append rmfiles " $odir/lt-${noexename}.c"
 	    fi
 	  fi
@@ -8348,5 +9598,4 @@
       func_show_eval "$RM $rmfiles" 'exit_status=1'
     done
-    objdir="$origobjdir"
 
     # Try to remove the ${objdir}s in the directories where we deleted files
@@ -8360,8 +9609,8 @@
 }
 
-{ test "$mode" = uninstall || test "$mode" = clean; } &&
+{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
     func_mode_uninstall ${1+"$@"}
 
-test -z "$mode" && {
+test -z "$opt_mode" && {
   help="$generic_help"
   func_fatal_help "you must specify a MODE"
@@ -8369,5 +9618,5 @@
 
 test -z "$exec_cmd" && \
-  func_fatal_help "invalid operation mode \`$mode'"
+  func_fatal_help "invalid operation mode \`$opt_mode'"
 
 if test -n "$exec_cmd"; then
Index: sm/branches/trunk-jpl-damage/m4/ar-lib.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ar-lib.m4	(revision 13100)
+++ 	(revision )
@@ -1,61 +1,0 @@
-##                                                          -*- Autoconf -*-
-# Copyright (C) 2011 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# serial 1
-
-# AM_PROG_AR([ACT-IF-FAIL])
-# -------------------------
-# Try to determine the archiver interface, and trigger the ar-lib wrapper
-# if it is needed.  If the detection of archiver interface fails, run
-# ACT-IF-FAIL (default is to abort configure with a proper error message).
-AC_DEFUN([AM_PROG_AR],
-[AC_BEFORE([$0], [LT_INIT])dnl
-AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl
-AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-AC_REQUIRE_AUX_FILE([ar-lib])dnl
-AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false])
-: ${AR=ar}
-
-AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface],
-  [am_cv_ar_interface=ar
-   AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])],
-     [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
-      AC_TRY_EVAL([am_ar_try])
-      if test "$ac_status" -eq 0; then
-        am_cv_ar_interface=ar
-      else
-        am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
-        AC_TRY_EVAL([am_ar_try])
-        if test "$ac_status" -eq 0; then
-          am_cv_ar_interface=lib
-        else
-          am_cv_ar_interface=unknown
-        fi
-      fi
-      rm -f conftest.lib libconftest.a
-     ])
-   ])
-
-case $am_cv_ar_interface in
-ar)
-  ;;
-lib)
-  # Microsoft lib, so override with the ar-lib wrapper script.
-  # FIXME: It is wrong to rewrite AR.
-  # But if we don't then we get into trouble of one sort or another.
-  # A longer-term fix would be to have automake use am__AR in this case,
-  # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something
-  # similar.
-  AR="$am_aux_dir/ar-lib $AR"
-  ;;
-unknown)
-  m4_default([$1],
-             [AC_MSG_ERROR([could not determine $AR interface])])
-  ;;
-esac
-AC_SUBST([AR])dnl
-])
Index: /issm/branches/trunk-jpl-damage/m4/issm_options.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/issm_options.m4	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/m4/issm_options.m4	(revision 13101)
@@ -15,9 +15,17 @@
 	dnl }}}
     dnl shared build {{{
-    AC_ARG_ENABLE([shared],                                                dnl feature
-        AS_HELP_STRING([--enable-shared], [produce libISSM.so.0]),         dnl help string
-        [enable_shared=$enableval],                                        dnl action if given
-        [enable_shared=no])                                                dnl action if not given
-    AM_CONDITIONAL([SHARED], [test $enable_shared = yes])
+    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
+        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
+        [enable_sharedlibs=$enableval],                                        dnl action if given
+        [enable_sharedlibs=no])                                                dnl action if not given
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+    dnl }}}
+
+    dnl shared build {{{
+    AC_ARG_ENABLE([version],                                                dnl feature
+        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
+        [enable_version=$enableval],                                        dnl action if given
+        [enable_version=no])                                                dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
     dnl }}}
 
@@ -221,5 +229,5 @@
 		MATLABWRAPPEREXT=$MEXEXT
 		AC_SUBST([MATLABWRAPPEREXT])
-		AC_SUBST([MEXLIB]) 
+	    AC_SUBST([MEXLIB]) 
 		AC_SUBST([MEXLINK])
 	fi
@@ -466,4 +474,13 @@
 	AC_MSG_RESULT($HAVE_ADOLC)
 	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
 	dnl adic2{{{
 	AC_ARG_WITH([adic2-dir],
@@ -589,5 +606,5 @@
 				;;
 			esac
-	
+
 			METISINCL=-I"$METIS_ROOT/include" 
 			AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
@@ -606,5 +623,5 @@
 	AC_MSG_CHECKING(for mpi)
 	AC_ARG_WITH([mpi-lib],
-		AS_HELP_STRING([--with-mpi-lib = otions],[mpi options, for ex: "-L$MPIROOT -lmpich]),
+		AS_HELP_STRING([--with-mpi-lib = options],[mpi options, for ex: "-L$MPIROOT -lmpich]),
 		[MPILIB=$withval],[MPILIB=""])
 	
@@ -620,5 +637,5 @@
 		else
 			HAVE_MPI=yes
-			MPIINCL=-I"$MPI_INCLUDE/"
+			MPIINCL=-I"$MPI_INCLUDE"
 			AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
 			AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
@@ -666,21 +683,21 @@
 			*cygwin*)
 			if test "$PETSC_MAJOR" = "2" ; then
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetscksp.lib  libpetscdm.lib  libpetscmat.lib  libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetscksp.lib  libpetscdm.lib  libpetscmat.lib  libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
 			else
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetsc.lib"
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetsc.lib"
 			fi
 			;;
 			*linux*)
 			if test "$PETSC_MAJOR" = "2" ; then
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
 			else
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc -ldl"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc -ldl"
 			fi
 			;;
 			*darwin*)
 			if test "$PETSC_MAJOR" = "2" ; then
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
 			else
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
 			fi
 			;;
Index: sm/branches/trunk-jpl-damage/m4/libtool.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/libtool.m4	(revision 13100)
+++ 	(revision )
@@ -1,7982 +1,0 @@
-# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
-#
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-m4_define([_LT_COPYING], [dnl
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of
-# the License, or (at your option) any later version.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
-#
-# GNU Libtool is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-])
-
-# serial 57 LT_INIT
-
-
-# LT_PREREQ(VERSION)
-# ------------------
-# Complain and exit if this libtool version is less that VERSION.
-m4_defun([LT_PREREQ],
-[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
-       [m4_default([$3],
-		   [m4_fatal([Libtool version $1 or higher is required],
-		             63)])],
-       [$2])])
-
-
-# _LT_CHECK_BUILDDIR
-# ------------------
-# Complain if the absolute build directory name contains unusual characters
-m4_defun([_LT_CHECK_BUILDDIR],
-[case `pwd` in
-  *\ * | *\	*)
-    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
-esac
-])
-
-
-# LT_INIT([OPTIONS])
-# ------------------
-AC_DEFUN([LT_INIT],
-[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
-AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
-AC_BEFORE([$0], [LT_LANG])dnl
-AC_BEFORE([$0], [LT_OUTPUT])dnl
-AC_BEFORE([$0], [LTDL_INIT])dnl
-m4_require([_LT_CHECK_BUILDDIR])dnl
-
-dnl Autoconf doesn't catch unexpanded LT_ macros by default:
-m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
-m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
-dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
-dnl unless we require an AC_DEFUNed macro:
-AC_REQUIRE([LTOPTIONS_VERSION])dnl
-AC_REQUIRE([LTSUGAR_VERSION])dnl
-AC_REQUIRE([LTVERSION_VERSION])dnl
-AC_REQUIRE([LTOBSOLETE_VERSION])dnl
-m4_require([_LT_PROG_LTMAIN])dnl
-
-_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
-
-dnl Parse OPTIONS
-_LT_SET_OPTIONS([$0], [$1])
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
-
-# Always use our own libtool.
-LIBTOOL='$(SHELL) $(top_builddir)/libtool'
-AC_SUBST(LIBTOOL)dnl
-
-_LT_SETUP
-
-# Only expand once:
-m4_define([LT_INIT])
-])# LT_INIT
-
-# Old names:
-AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
-AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
-dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
-
-
-# _LT_CC_BASENAME(CC)
-# -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
-m4_defun([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
-])
-
-
-# _LT_FILEUTILS_DEFAULTS
-# ----------------------
-# It is okay to use these file commands and assume they have been set
-# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
-m4_defun([_LT_FILEUTILS_DEFAULTS],
-[: ${CP="cp -f"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
-])# _LT_FILEUTILS_DEFAULTS
-
-
-# _LT_SETUP
-# ---------
-m4_defun([_LT_SETUP],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
-AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
-
-_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
-dnl
-_LT_DECL([], [host_alias], [0], [The host system])dnl
-_LT_DECL([], [host], [0])dnl
-_LT_DECL([], [host_os], [0])dnl
-dnl
-_LT_DECL([], [build_alias], [0], [The build system])dnl
-_LT_DECL([], [build], [0])dnl
-_LT_DECL([], [build_os], [0])dnl
-dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-dnl
-AC_REQUIRE([AC_PROG_LN_S])dnl
-test -z "$LN_S" && LN_S="ln -s"
-_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
-dnl
-AC_REQUIRE([LT_CMD_MAX_LEN])dnl
-_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
-_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
-dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_CHECK_SHELL_FEATURES])dnl
-m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
-m4_require([_LT_CMD_RELOAD])dnl
-m4_require([_LT_CHECK_MAGIC_METHOD])dnl
-m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
-m4_require([_LT_CMD_OLD_ARCHIVE])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-m4_require([_LT_WITH_SYSROOT])dnl
-
-_LT_CONFIG_LIBTOOL_INIT([
-# See if we are running on zsh, and set the options which allow our
-# commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-])
-if test -n "${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-
-_LT_CHECK_OBJDIR
-
-m4_require([_LT_TAG_COMPILER])dnl
-
-case $host_os in
-aix3*)
-  # AIX sometimes has problems with the GCC collect2 program.  For some
-  # reason, if we set the COLLECT_NAMES environment variable, the problems
-  # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
-    COLLECT_NAMES=
-    export COLLECT_NAMES
-  fi
-  ;;
-esac
-
-# Global variables:
-ofile=libtool
-can_build_shared=yes
-
-# All known linkers require a `.a' archive for static linking (except MSVC,
-# which needs '.lib').
-libext=a
-
-with_gnu_ld="$lt_cv_prog_gnu_ld"
-
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
-
-# Set sane defaults for various variables
-test -z "$CC" && CC=cc
-test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
-test -z "$LD" && LD=ld
-test -z "$ac_objext" && ac_objext=o
-
-_LT_CC_BASENAME([$compiler])
-
-# Only perform the check for file, if the check method requires it
-test -z "$MAGIC_CMD" && MAGIC_CMD=file
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    _LT_PATH_MAGIC
-  fi
-  ;;
-esac
-
-# Use C for the default configuration in the libtool script
-LT_SUPPORTED_TAG([CC])
-_LT_LANG_C_CONFIG
-_LT_LANG_DEFAULT_CONFIG
-_LT_CONFIG_COMMANDS
-])# _LT_SETUP
-
-
-# _LT_PREPARE_SED_QUOTE_VARS
-# --------------------------
-# Define a few sed substitution that help us do robust quoting.
-m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
-[# Backslashify metacharacters that are still active within
-# double-quoted strings.
-sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\([["`\\]]\)/\\\1/g'
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to delay expansion of an escaped single quote.
-delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst='s/\*/\\\*/g'
-])
-
-# _LT_PROG_LTMAIN
-# ---------------
-# Note that this code is called both from `configure', and `config.status'
-# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
-# `config.status' has no value for ac_aux_dir unless we are using Automake,
-# so we pass a copy along to make sure it has a sensible value anyway.
-m4_defun([_LT_PROG_LTMAIN],
-[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
-_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
-ltmain="$ac_aux_dir/ltmain.sh"
-])# _LT_PROG_LTMAIN
-
-
-## ------------------------------------- ##
-## Accumulate code for creating libtool. ##
-## ------------------------------------- ##
-
-# So that we can recreate a full libtool script including additional
-# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
-# in macros and then make a single call at the end using the `libtool'
-# label.
-
-
-# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
-# ----------------------------------------
-# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL_INIT],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_INIT])
-
-
-# _LT_CONFIG_LIBTOOL([COMMANDS])
-# ------------------------------
-# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
-
-
-# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
-# -----------------------------------------------------
-m4_defun([_LT_CONFIG_SAVE_COMMANDS],
-[_LT_CONFIG_LIBTOOL([$1])
-_LT_CONFIG_LIBTOOL_INIT([$2])
-])
-
-
-# _LT_FORMAT_COMMENT([COMMENT])
-# -----------------------------
-# Add leading comment marks to the start of each line, and a trailing
-# full-stop to the whole comment if one is not present already.
-m4_define([_LT_FORMAT_COMMENT],
-[m4_ifval([$1], [
-m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
-              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
-)])
-
-
-
-## ------------------------ ##
-## FIXME: Eliminate VARNAME ##
-## ------------------------ ##
-
-
-# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
-# -------------------------------------------------------------------
-# CONFIGNAME is the name given to the value in the libtool script.
-# VARNAME is the (base) name used in the configure script.
-# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
-# VARNAME.  Any other value will be used directly.
-m4_define([_LT_DECL],
-[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
-    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
-	[m4_ifval([$1], [$1], [$2])])
-    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
-    m4_ifval([$4],
-	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
-    lt_dict_add_subkey([lt_decl_dict], [$2],
-	[tagged?], [m4_ifval([$5], [yes], [no])])])
-])
-
-
-# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
-# --------------------------------------------------------
-m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
-
-
-# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_tag_varnames],
-[_lt_decl_filter([tagged?], [yes], $@)])
-
-
-# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
-# ---------------------------------------------------------
-m4_define([_lt_decl_filter],
-[m4_case([$#],
-  [0], [m4_fatal([$0: too few arguments: $#])],
-  [1], [m4_fatal([$0: too few arguments: $#: $1])],
-  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
-  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
-  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
-])
-
-
-# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
-# --------------------------------------------------
-m4_define([lt_decl_quote_varnames],
-[_lt_decl_filter([value], [1], $@)])
-
-
-# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_dquote_varnames],
-[_lt_decl_filter([value], [2], $@)])
-
-
-# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_varnames_tagged],
-[m4_assert([$# <= 2])dnl
-_$0(m4_quote(m4_default([$1], [[, ]])),
-    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
-    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
-m4_define([_lt_decl_varnames_tagged],
-[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
-
-
-# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_all_varnames],
-[_$0(m4_quote(m4_default([$1], [[, ]])),
-     m4_if([$2], [],
-	   m4_quote(lt_decl_varnames),
-	m4_quote(m4_shift($@))))[]dnl
-])
-m4_define([_lt_decl_all_varnames],
-[lt_join($@, lt_decl_varnames_tagged([$1],
-			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
-])
-
-
-# _LT_CONFIG_STATUS_DECLARE([VARNAME])
-# ------------------------------------
-# Quote a variable value, and forward it to `config.status' so that its
-# declaration there will have the same value as in `configure'.  VARNAME
-# must have a single quote delimited value for this to work.
-m4_define([_LT_CONFIG_STATUS_DECLARE],
-[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
-
-
-# _LT_CONFIG_STATUS_DECLARATIONS
-# ------------------------------
-# We delimit libtool config variables with single quotes, so when
-# we write them to config.status, we have to be sure to quote all
-# embedded single quotes properly.  In configure, this macro expands
-# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
-#
-#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
-m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
-    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAGS
-# ----------------
-# Output comment and list of tags supported by the script
-m4_defun([_LT_LIBTOOL_TAGS],
-[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
-available_tags="_LT_TAGS"dnl
-])
-
-
-# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
-# -----------------------------------
-# Extract the dictionary values for VARNAME (optionally with TAG) and
-# expand to a commented shell variable setting:
-#
-#    # Some comment about what VAR is for.
-#    visible_name=$lt_internal_name
-m4_define([_LT_LIBTOOL_DECLARE],
-[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
-					   [description])))[]dnl
-m4_pushdef([_libtool_name],
-    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
-m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
-    [0], [_libtool_name=[$]$1],
-    [1], [_libtool_name=$lt_[]$1],
-    [2], [_libtool_name=$lt_[]$1],
-    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
-m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
-])
-
-
-# _LT_LIBTOOL_CONFIG_VARS
-# -----------------------
-# Produce commented declarations of non-tagged libtool config variables
-# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
-# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
-# section) are produced by _LT_LIBTOOL_TAG_VARS.
-m4_defun([_LT_LIBTOOL_CONFIG_VARS],
-[m4_foreach([_lt_var],
-    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAG_VARS(TAG)
-# -------------------------
-m4_define([_LT_LIBTOOL_TAG_VARS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
-
-
-# _LT_TAGVAR(VARNAME, [TAGNAME])
-# ------------------------------
-m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
-
-
-# _LT_CONFIG_COMMANDS
-# -------------------
-# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
-# variables for single and double quote escaping we saved from calls
-# to _LT_DECL, we can put quote escaped variables declarations
-# into `config.status', and then the shell code to quote escape them in
-# for loops in `config.status'.  Finally, any additional code accumulated
-# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
-m4_defun([_LT_CONFIG_COMMANDS],
-[AC_PROVIDE_IFELSE([LT_OUTPUT],
-	dnl If the libtool generation code has been placed in $CONFIG_LT,
-	dnl instead of duplicating it all over again into config.status,
-	dnl then we will have config.status run $CONFIG_LT later, so it
-	dnl needs to know what name is stored there:
-        [AC_CONFIG_COMMANDS([libtool],
-            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
-    dnl If the libtool generation code is destined for config.status,
-    dnl expand the accumulated commands and init code now:
-    [AC_CONFIG_COMMANDS([libtool],
-        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
-])#_LT_CONFIG_COMMANDS
-
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
-[
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-sed_quote_subst='$sed_quote_subst'
-double_quote_subst='$double_quote_subst'
-delay_variable_subst='$delay_variable_subst'
-_LT_CONFIG_STATUS_DECLARATIONS
-LTCC='$LTCC'
-LTCFLAGS='$LTCFLAGS'
-compiler='$compiler_DEFAULT'
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-\$[]1
-_LTECHO_EOF'
-}
-
-# Quote evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_quote_varnames); do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-# Double-quote double-evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_dquote_varnames); do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-_LT_OUTPUT_LIBTOOL_INIT
-])
-
-# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
-# ------------------------------------
-# Generate a child script FILE with all initialization necessary to
-# reuse the environment learned by the parent script, and make the
-# file executable.  If COMMENT is supplied, it is inserted after the
-# `#!' sequence but before initialization text begins.  After this
-# macro, additional text can be appended to FILE to form the body of
-# the child script.  The macro ends with non-zero status if the
-# file could not be fully written (such as if the disk is full).
-m4_ifdef([AS_INIT_GENERATED],
-[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
-[m4_defun([_LT_GENERATED_FILE_INIT],
-[m4_require([AS_PREPARE])]dnl
-[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
-[lt_write_fail=0
-cat >$1 <<_ASEOF || lt_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-$2
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$1 <<\_ASEOF || lt_write_fail=1
-AS_SHELL_SANITIZE
-_AS_PREPARE
-exec AS_MESSAGE_FD>&1
-_ASEOF
-test $lt_write_fail = 0 && chmod +x $1[]dnl
-m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
-
-# LT_OUTPUT
-# ---------
-# This macro allows early generation of the libtool script (before
-# AC_OUTPUT is called), incase it is used in configure for compilation
-# tests.
-AC_DEFUN([LT_OUTPUT],
-[: ${CONFIG_LT=./config.lt}
-AC_MSG_NOTICE([creating $CONFIG_LT])
-_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
-[# Run this file to recreate a libtool stub with the current configuration.])
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-lt_cl_silent=false
-exec AS_MESSAGE_LOG_FD>>config.log
-{
-  echo
-  AS_BOX([Running $as_me.])
-} >&AS_MESSAGE_LOG_FD
-
-lt_cl_help="\
-\`$as_me' creates a local libtool stub from the current configuration,
-for use in further configure time tests before the real libtool is
-generated.
-
-Usage: $[0] [[OPTIONS]]
-
-  -h, --help      print this help, then exit
-  -V, --version   print version number, then exit
-  -q, --quiet     do not print progress messages
-  -d, --debug     don't remove temporary files
-
-Report bugs to <bug-libtool@gnu.org>."
-
-lt_cl_version="\
-m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
-m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
-configured by $[0], generated by m4_PACKAGE_STRING.
-
-Copyright (C) 2011 Free Software Foundation, Inc.
-This config.lt script is free software; the Free Software Foundation
-gives unlimited permision to copy, distribute and modify it."
-
-while test $[#] != 0
-do
-  case $[1] in
-    --version | --v* | -V )
-      echo "$lt_cl_version"; exit 0 ;;
-    --help | --h* | -h )
-      echo "$lt_cl_help"; exit 0 ;;
-    --debug | --d* | -d )
-      debug=: ;;
-    --quiet | --q* | --silent | --s* | -q )
-      lt_cl_silent=: ;;
-
-    -*) AC_MSG_ERROR([unrecognized option: $[1]
-Try \`$[0] --help' for more information.]) ;;
-
-    *) AC_MSG_ERROR([unrecognized argument: $[1]
-Try \`$[0] --help' for more information.]) ;;
-  esac
-  shift
-done
-
-if $lt_cl_silent; then
-  exec AS_MESSAGE_FD>/dev/null
-fi
-_LTEOF
-
-cat >>"$CONFIG_LT" <<_LTEOF
-_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
-_LTEOF
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-AC_MSG_NOTICE([creating $ofile])
-_LT_OUTPUT_LIBTOOL_COMMANDS
-AS_EXIT(0)
-_LTEOF
-chmod +x "$CONFIG_LT"
-
-# configure is writing to config.log, but config.lt does its own redirection,
-# appending to config.log, which fails on DOS, as config.log is still kept
-# open by configure.  Here we exec the FD to /dev/null, effectively closing
-# config.log, so it can be properly (re)opened and appended to by config.lt.
-lt_cl_success=:
-test "$silent" = yes &&
-  lt_config_lt_args="$lt_config_lt_args --quiet"
-exec AS_MESSAGE_LOG_FD>/dev/null
-$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
-exec AS_MESSAGE_LOG_FD>>config.log
-$lt_cl_success || AS_EXIT(1)
-])# LT_OUTPUT
-
-
-# _LT_CONFIG(TAG)
-# ---------------
-# If TAG is the built-in tag, create an initial libtool script with a
-# default configuration from the untagged config vars.  Otherwise add code
-# to config.status for appending the configuration named by TAG from the
-# matching tagged config vars.
-m4_defun([_LT_CONFIG],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_CONFIG_SAVE_COMMANDS([
-  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
-  m4_if(_LT_TAG, [C], [
-    # See if we are running on zsh, and set the options which allow our
-    # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
-      setopt NO_GLOB_SUBST
-    fi
-
-    cfgfile="${ofile}T"
-    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
-    $RM "$cfgfile"
-
-    cat <<_LT_EOF >> "$cfgfile"
-#! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-_LT_COPYING
-_LT_LIBTOOL_TAGS
-
-# ### BEGIN LIBTOOL CONFIG
-_LT_LIBTOOL_CONFIG_VARS
-_LT_LIBTOOL_TAG_VARS
-# ### END LIBTOOL CONFIG
-
-_LT_EOF
-
-  case $host_os in
-  aix3*)
-    cat <<\_LT_EOF >> "$cfgfile"
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
-  COLLECT_NAMES=
-  export COLLECT_NAMES
-fi
-_LT_EOF
-    ;;
-  esac
-
-  _LT_PROG_LTMAIN
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # text mode, it properly converts lines to CR/LF.  This bash problem
-  # is reportedly fixed, but why not run on old versions too?
-  sed '$q' "$ltmain" >> "$cfgfile" \
-     || (rm -f "$cfgfile"; exit 1)
-
-  _LT_PROG_REPLACE_SHELLFNS
-
-   mv -f "$cfgfile" "$ofile" ||
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-],
-[cat <<_LT_EOF >> "$ofile"
-
-dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
-dnl in a comment (ie after a #).
-# ### BEGIN LIBTOOL TAG CONFIG: $1
-_LT_LIBTOOL_TAG_VARS(_LT_TAG)
-# ### END LIBTOOL TAG CONFIG: $1
-_LT_EOF
-])dnl /m4_if
-],
-[m4_if([$1], [], [
-    PACKAGE='$PACKAGE'
-    VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
-    RM='$RM'
-    ofile='$ofile'], [])
-])dnl /_LT_CONFIG_SAVE_COMMANDS
-])# _LT_CONFIG
-
-
-# LT_SUPPORTED_TAG(TAG)
-# ---------------------
-# Trace this macro to discover what tags are supported by the libtool
-# --tag option, using:
-#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
-AC_DEFUN([LT_SUPPORTED_TAG], [])
-
-
-# C support is built-in for now
-m4_define([_LT_LANG_C_enabled], [])
-m4_define([_LT_TAGS], [])
-
-
-# LT_LANG(LANG)
-# -------------
-# Enable libtool support for the given language if not already enabled.
-AC_DEFUN([LT_LANG],
-[AC_BEFORE([$0], [LT_OUTPUT])dnl
-m4_case([$1],
-  [C],			[_LT_LANG(C)],
-  [C++],		[_LT_LANG(CXX)],
-  [Go],			[_LT_LANG(GO)],
-  [Java],		[_LT_LANG(GCJ)],
-  [Fortran 77],		[_LT_LANG(F77)],
-  [Fortran],		[_LT_LANG(FC)],
-  [Windows Resource],	[_LT_LANG(RC)],
-  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
-    [_LT_LANG($1)],
-    [m4_fatal([$0: unsupported language: "$1"])])])dnl
-])# LT_LANG
-
-
-# _LT_LANG(LANGNAME)
-# ------------------
-m4_defun([_LT_LANG],
-[m4_ifdef([_LT_LANG_]$1[_enabled], [],
-  [LT_SUPPORTED_TAG([$1])dnl
-  m4_append([_LT_TAGS], [$1 ])dnl
-  m4_define([_LT_LANG_]$1[_enabled], [])dnl
-  _LT_LANG_$1_CONFIG($1)])dnl
-])# _LT_LANG
-
-
-m4_ifndef([AC_PROG_GO], [
-############################################################
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-############################################################
-m4_defun([AC_PROG_GO],
-[AC_LANG_PUSH(Go)dnl
-AC_ARG_VAR([GOC],     [Go compiler command])dnl
-AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
-_AC_ARG_VAR_LDFLAGS()dnl
-AC_CHECK_TOOL(GOC, gccgo)
-if test -z "$GOC"; then
-  if test -n "$ac_tool_prefix"; then
-    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
-  fi
-fi
-if test -z "$GOC"; then
-  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
-fi
-])#m4_defun
-])#m4_ifndef
-
-
-# _LT_LANG_DEFAULT_CONFIG
-# -----------------------
-m4_defun([_LT_LANG_DEFAULT_CONFIG],
-[AC_PROVIDE_IFELSE([AC_PROG_CXX],
-  [LT_LANG(CXX)],
-  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_F77],
-  [LT_LANG(F77)],
-  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_FC],
-  [LT_LANG(FC)],
-  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
-
-dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
-dnl pulling things in needlessly.
-AC_PROVIDE_IFELSE([AC_PROG_GCJ],
-  [LT_LANG(GCJ)],
-  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
-    [LT_LANG(GCJ)],
-    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
-      [LT_LANG(GCJ)],
-      [m4_ifdef([AC_PROG_GCJ],
-	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([A][M_PROG_GCJ],
-	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([LT_PROG_GCJ],
-	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
-
-AC_PROVIDE_IFELSE([AC_PROG_GO],
-  [LT_LANG(GO)],
-  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
-
-AC_PROVIDE_IFELSE([LT_PROG_RC],
-  [LT_LANG(RC)],
-  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
-])# _LT_LANG_DEFAULT_CONFIG
-
-# Obsolete macros:
-AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
-AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
-AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
-AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
-AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
-dnl AC_DEFUN([AC_LIBTOOL_F77], [])
-dnl AC_DEFUN([AC_LIBTOOL_FC], [])
-dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
-dnl AC_DEFUN([AC_LIBTOOL_RC], [])
-
-
-# _LT_TAG_COMPILER
-# ----------------
-m4_defun([_LT_TAG_COMPILER],
-[AC_REQUIRE([AC_PROG_CC])dnl
-
-_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
-_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
-_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
-_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-])# _LT_TAG_COMPILER
-
-
-# _LT_COMPILER_BOILERPLATE
-# ------------------------
-# Check for compiler boilerplate output or warnings with
-# the simple compiler test code.
-m4_defun([_LT_COMPILER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$RM conftest*
-])# _LT_COMPILER_BOILERPLATE
-
-
-# _LT_LINKER_BOILERPLATE
-# ----------------------
-# Check for linker boilerplate output or warnings with
-# the simple link test code.
-m4_defun([_LT_LINKER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$RM -r conftest*
-])# _LT_LINKER_BOILERPLATE
-
-# _LT_REQUIRED_DARWIN_CHECKS
-# -------------------------
-m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
-  case $host_os in
-    rhapsody* | darwin*)
-    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
-    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
-    AC_CHECK_TOOL([LIPO], [lipo], [:])
-    AC_CHECK_TOOL([OTOOL], [otool], [:])
-    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
-    _LT_DECL([], [DSYMUTIL], [1],
-      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
-    _LT_DECL([], [NMEDIT], [1],
-      [Tool to change global to local symbols on Mac OS X])
-    _LT_DECL([], [LIPO], [1],
-      [Tool to manipulate fat objects and archives on Mac OS X])
-    _LT_DECL([], [OTOOL], [1],
-      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
-    _LT_DECL([], [OTOOL64], [1],
-      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
-
-    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
-      [lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
-	# By default we will add the -single_module flag. You can override
-	# by either setting the environment variable LT_MULTI_MODULE
-	# non-empty at configure time, or by adding -multi_module to the
-	# link flags.
-	rm -rf libconftest.dylib*
-	echo "int foo(void){return 1;}" > conftest.c
-	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
--dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
-	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
-	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
-        _lt_result=$?
-	# If there is a non-empty error log, and "single_module"
-	# appears in it, assume the flag caused a linker warning
-        if test -s conftest.err && $GREP single_module conftest.err; then
-	  cat conftest.err >&AS_MESSAGE_LOG_FD
-	# Otherwise, if the output was created with a 0 exit code from
-	# the compiler, it worked.
-	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
-	  lt_cv_apple_cc_single_mod=yes
-	else
-	  cat conftest.err >&AS_MESSAGE_LOG_FD
-	fi
-	rm -rf libconftest.dylib*
-	rm -f conftest.*
-      fi])
-
-    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
-      [lt_cv_ld_exported_symbols_list],
-      [lt_cv_ld_exported_symbols_list=no
-      save_LDFLAGS=$LDFLAGS
-      echo "_main" > conftest.sym
-      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
-      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-	[lt_cv_ld_exported_symbols_list=yes],
-	[lt_cv_ld_exported_symbols_list=no])
-	LDFLAGS="$save_LDFLAGS"
-    ])
-
-    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
-      [lt_cv_ld_force_load=no
-      cat > conftest.c << _LT_EOF
-int forced_loaded() { return 2;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
-      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
-      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
-      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
-      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
-      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
-      cat > conftest.c << _LT_EOF
-int main() { return 0;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
-      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
-      _lt_result=$?
-      if test -s conftest.err && $GREP force_load conftest.err; then
-	cat conftest.err >&AS_MESSAGE_LOG_FD
-      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
-	lt_cv_ld_force_load=yes
-      else
-	cat conftest.err >&AS_MESSAGE_LOG_FD
-      fi
-        rm -f conftest.err libconftest.a conftest conftest.c
-        rm -rf conftest.dSYM
-    ])
-    case $host_os in
-    rhapsody* | darwin1.[[012]])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
-    darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-    darwin*) # darwin 5.x on
-      # if running on 10.5 or later, the deployment target defaults
-      # to the OS version, if on x86, and 10.4, the deployment
-      # target defaults to 10.4. Don't you love it?
-      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
-	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[[012]]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-      esac
-    ;;
-  esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
-      _lt_dar_single_mod='$single_module'
-    fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
-    else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    fi
-    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
-      _lt_dsymutil='~$DSYMUTIL $lib || :'
-    else
-      _lt_dsymutil=
-    fi
-    ;;
-  esac
-])
-
-
-# _LT_DARWIN_LINKER_FEATURES([TAG])
-# ---------------------------------
-# Checks for linker and compiler features on darwin
-m4_defun([_LT_DARWIN_LINKER_FEATURES],
-[
-  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _LT_TAGVAR(hardcode_automatic, $1)=yes
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  if test "$lt_cv_ld_force_load" = "yes"; then
-    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
-    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
-                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
-  else
-    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
-  fi
-  _LT_TAGVAR(link_all_deplibs, $1)=yes
-  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
-  case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
-     *) _lt_dar_can_shared=$GCC ;;
-  esac
-  if test "$_lt_dar_can_shared" = "yes"; then
-    output_verbose_link_cmd=func_echo_all
-    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
-    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
-    m4_if([$1], [CXX],
-[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
-      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
-      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
-    fi
-],[])
-  else
-  _LT_TAGVAR(ld_shlibs, $1)=no
-  fi
-])
-
-# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
-# ----------------------------------
-# Links a minimal program and checks the executable
-# for the system default hardcoded library path. In most cases,
-# this is /usr/lib:/lib, but when the MPI compilers are used
-# the location of the communication and MPI libs are included too.
-# If we don't find anything, use the default library path according
-# to the aix ld manual.
-# Store the results from the different compilers for each TAGNAME.
-# Allow to override them for all tags through lt_cv_aix_libpath.
-m4_defun([_LT_SYS_MODULE_PATH_AIX],
-[m4_require([_LT_DECL_SED])dnl
-if test "${lt_cv_aix_libpath+set}" = set; then
-  aix_libpath=$lt_cv_aix_libpath
-else
-  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
-  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
-  lt_aix_libpath_sed='[
-      /Import File Strings/,/^$/ {
-	  /^0/ {
-	      s/^0  *\([^ ]*\) *$/\1/
-	      p
-	  }
-      }]'
-  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  # Check for a 64-bit object if we didn't find anything.
-  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
-    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  fi],[])
-  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
-    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
-  fi
-  ])
-  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
-fi
-])# _LT_SYS_MODULE_PATH_AIX
-
-
-# _LT_SHELL_INIT(ARG)
-# -------------------
-m4_define([_LT_SHELL_INIT],
-[m4_divert_text([M4SH-INIT], [$1
-])])# _LT_SHELL_INIT
-
-
-
-# _LT_PROG_ECHO_BACKSLASH
-# -----------------------
-# Find how we can fake an echo command that does not interpret backslash.
-# In particular, with Autoconf 2.60 or later we add some code to the start
-# of the generated configure script which will find a shell with a builtin
-# printf (which we can use as an echo command).
-m4_defun([_LT_PROG_ECHO_BACKSLASH],
-[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
-
-AC_MSG_CHECKING([how to print strings])
-# Test print first, because it will be a builtin if present.
-if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
-   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='print -r --'
-elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='printf %s\n'
-else
-  # Use this function as a fallback that always works.
-  func_fallback_echo ()
-  {
-    eval 'cat <<_LTECHO_EOF
-$[]1
-_LTECHO_EOF'
-  }
-  ECHO='func_fallback_echo'
-fi
-
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO "$*" 
-}
-
-case "$ECHO" in
-  printf*) AC_MSG_RESULT([printf]) ;;
-  print*) AC_MSG_RESULT([print -r]) ;;
-  *) AC_MSG_RESULT([cat]) ;;
-esac
-
-m4_ifdef([_AS_DETECT_SUGGESTED],
-[_AS_DETECT_SUGGESTED([
-  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
-    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
-    PATH=/empty FPATH=/empty; export PATH FPATH
-    test "X`printf %s $ECHO`" = "X$ECHO" \
-      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
-
-_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
-_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
-])# _LT_PROG_ECHO_BACKSLASH
-
-
-# _LT_WITH_SYSROOT
-# ----------------
-AC_DEFUN([_LT_WITH_SYSROOT],
-[AC_MSG_CHECKING([for sysroot])
-AC_ARG_WITH([sysroot],
-[  --with-sysroot[=DIR] Search for dependent libraries within DIR
-                        (or the compiler's sysroot if not specified).],
-[], [with_sysroot=no])
-
-dnl lt_sysroot will always be passed unquoted.  We quote it here
-dnl in case the user passed a directory name.
-lt_sysroot=
-case ${with_sysroot} in #(
- yes)
-   if test "$GCC" = yes; then
-     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
-   fi
-   ;; #(
- /*)
-   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
-   ;; #(
- no|'')
-   ;; #(
- *)
-   AC_MSG_RESULT([${with_sysroot}])
-   AC_MSG_ERROR([The sysroot must be an absolute path.])
-   ;;
-esac
-
- AC_MSG_RESULT([${lt_sysroot:-no}])
-_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
-[dependent libraries, and in which our libraries should be installed.])])
-
-# _LT_ENABLE_LOCK
-# ---------------
-m4_defun([_LT_ENABLE_LOCK],
-[AC_ARG_ENABLE([libtool-lock],
-  [AS_HELP_STRING([--disable-libtool-lock],
-    [avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.$ac_objext` in
-      *ELF-32*)
-	HPUX_IA64_MODE="32"
-	;;
-      *ELF-64*)
-	HPUX_IA64_MODE="64"
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -melf32bsmip"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -melf32bmipn32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -melf64bmip"
-	;;
-      esac
-    else
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -32"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -n32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -64"
-	  ;;
-      esac
-    fi
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
-s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-      *32-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_i386_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_i386"
-	    ;;
-	  ppc64-*linux*|powerpc64-*linux*)
-	    LD="${LD-ld} -m elf32ppclinux"
-	    ;;
-	  s390x-*linux*)
-	    LD="${LD-ld} -m elf_s390"
-	    ;;
-	  sparc64-*linux*)
-	    LD="${LD-ld} -m elf32_sparc"
-	    ;;
-	esac
-	;;
-      *64-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_x86_64_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_x86_64"
-	    ;;
-	  ppc*-*linux*|powerpc*-*linux*)
-	    LD="${LD-ld} -m elf64ppc"
-	    ;;
-	  s390*-*linux*|s390*-*tpf*)
-	    LD="${LD-ld} -m elf64_s390"
-	    ;;
-	  sparc*-*linux*)
-	    LD="${LD-ld} -m elf64_sparc"
-	    ;;
-	esac
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS -belf"
-  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
-    [AC_LANG_PUSH(C)
-     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
-     AC_LANG_POP])
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
-  fi
-  ;;
-*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*)
-        case $host in
-        i?86-*-solaris*)
-          LD="${LD-ld} -m elf_x86_64"
-          ;;
-        sparc*-*-solaris*)
-          LD="${LD-ld} -m elf64_sparc"
-          ;;
-        esac
-        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
-        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
-          LD="${LD-ld}_sol2"
-        fi
-        ;;
-      *)
-	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
-	  LD="${LD-ld} -64"
-	fi
-	;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-esac
-
-need_locks="$enable_libtool_lock"
-])# _LT_ENABLE_LOCK
-
-
-# _LT_PROG_AR
-# -----------
-m4_defun([_LT_PROG_AR],
-[AC_CHECK_TOOLS(AR, [ar], false)
-: ${AR=ar}
-: ${AR_FLAGS=cru}
-_LT_DECL([], [AR], [1], [The archiver])
-_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
-
-AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
-  [lt_cv_ar_at_file=no
-   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
-     [echo conftest.$ac_objext > conftest.lst
-      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
-      AC_TRY_EVAL([lt_ar_try])
-      if test "$ac_status" -eq 0; then
-	# Ensure the archiver fails upon bogus file names.
-	rm -f conftest.$ac_objext libconftest.a
-	AC_TRY_EVAL([lt_ar_try])
-	if test "$ac_status" -ne 0; then
-          lt_cv_ar_at_file=@
-        fi
-      fi
-      rm -f conftest.* libconftest.a
-     ])
-  ])
-
-if test "x$lt_cv_ar_at_file" = xno; then
-  archiver_list_spec=
-else
-  archiver_list_spec=$lt_cv_ar_at_file
-fi
-_LT_DECL([], [archiver_list_spec], [1],
-  [How to feed a file listing to the archiver])
-])# _LT_PROG_AR
-
-
-# _LT_CMD_OLD_ARCHIVE
-# -------------------
-m4_defun([_LT_CMD_OLD_ARCHIVE],
-[_LT_PROG_AR
-
-AC_CHECK_TOOL(STRIP, strip, :)
-test -z "$STRIP" && STRIP=:
-_LT_DECL([], [STRIP], [1], [A symbol stripping program])
-
-AC_CHECK_TOOL(RANLIB, ranlib, :)
-test -z "$RANLIB" && RANLIB=:
-_LT_DECL([], [RANLIB], [1],
-    [Commands used to install an old-style archive])
-
-# Determine commands to create old-style static archives.
-old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
-old_postinstall_cmds='chmod 644 $oldlib'
-old_postuninstall_cmds=
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
-    ;;
-  *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
-    ;;
-  esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
-fi
-
-case $host_os in
-  darwin*)
-    lock_old_archive_extraction=yes ;;
-  *)
-    lock_old_archive_extraction=no ;;
-esac
-_LT_DECL([], [old_postinstall_cmds], [2])
-_LT_DECL([], [old_postuninstall_cmds], [2])
-_LT_TAGDECL([], [old_archive_cmds], [2],
-    [Commands used to build an old-style archive])
-_LT_DECL([], [lock_old_archive_extraction], [0],
-    [Whether to use a lock for old archive extraction])
-])# _LT_CMD_OLD_ARCHIVE
-
-
-# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------------------
-# Check whether the given compiler option works
-AC_DEFUN([_LT_COMPILER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$3"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=$?
-   cat conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       $2=yes
-     fi
-   fi
-   $RM conftest*
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$5], , :, [$5])
-else
-    m4_if([$6], , :, [$6])
-fi
-])# _LT_COMPILER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
-
-
-# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#                  [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------
-# Check whether the given linker option works
-AC_DEFUN([_LT_LINKER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $3"
-   echo "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&AS_MESSAGE_LOG_FD
-       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         $2=yes
-       fi
-     else
-       $2=yes
-     fi
-   fi
-   $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$4], , :, [$4])
-else
-    m4_if([$5], , :, [$5])
-fi
-])# _LT_LINKER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
-
-
-# LT_CMD_MAX_LEN
-#---------------
-AC_DEFUN([LT_CMD_MAX_LEN],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-# find the maximum length of command line arguments
-AC_MSG_CHECKING([the maximum length of command line arguments])
-AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
-  i=0
-  teststring="ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=-1;
-    ;;
-
-  cygwin* | mingw* | cegcc*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  mint*)
-    # On MiNT this can take a long time and run out of memory.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
-
-  os2*)
-    # The test takes a long time on OS/2.
-    lt_cv_sys_max_cmd_len=8192
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
-  *)
-    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
-    if test -n "$lt_cv_sys_max_cmd_len"; then
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    else
-      # Make teststring a little bigger before we do anything with it.
-      # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
-        teststring=$teststring$teststring
-      done
-      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
-      # If test is not a shell built-in, we'll probably end up computing a
-      # maximum length that is only half of the actual maximum length, but
-      # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
-	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
-      do
-        i=`expr $i + 1`
-        teststring=$teststring$teststring
-      done
-      # Only check the string length outside the loop.
-      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
-      teststring=
-      # Add a significant safety factor because C++ compilers can tack on
-      # massive amounts of additional arguments before passing them to the
-      # linker.  It appears as though 1/2 is a usable value.
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
-    fi
-    ;;
-  esac
-])
-if test -n $lt_cv_sys_max_cmd_len ; then
-  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
-else
-  AC_MSG_RESULT(none)
-fi
-max_cmd_len=$lt_cv_sys_max_cmd_len
-_LT_DECL([], [max_cmd_len], [0],
-    [What is the maximum length of a command?])
-])# LT_CMD_MAX_LEN
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
-
-
-# _LT_HEADER_DLFCN
-# ----------------
-m4_defun([_LT_HEADER_DLFCN],
-[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
-])# _LT_HEADER_DLFCN
-
-
-# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
-#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
-# ----------------------------------------------------------------
-m4_defun([_LT_TRY_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "$cross_compiling" = yes; then :
-  [$4]
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-[#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}]
-_LT_EOF
-  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) $1 ;;
-      x$lt_dlneed_uscore) $2 ;;
-      x$lt_dlunknown|x*) $3 ;;
-    esac
-  else :
-    # compilation failed
-    $3
-  fi
-fi
-rm -fr conftest*
-])# _LT_TRY_DLOPEN_SELF
-
-
-# LT_SYS_DLOPEN_SELF
-# ------------------
-AC_DEFUN([LT_SYS_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "x$enable_dlopen" != xyes; then
-  enable_dlopen=unknown
-  enable_dlopen_self=unknown
-  enable_dlopen_self_static=unknown
-else
-  lt_cv_dlopen=no
-  lt_cv_dlopen_libs=
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen="load_add_on"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ;;
-
-  mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
-    lt_cv_dlopen_libs=
-    ;;
-
-  cygwin*)
-    lt_cv_dlopen="dlopen"
-    lt_cv_dlopen_libs=
-    ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
-    lt_cv_dlopen="dyld"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ])
-    ;;
-
-  *)
-    AC_CHECK_FUNC([shl_load],
-	  [lt_cv_dlopen="shl_load"],
-      [AC_CHECK_LIB([dld], [shl_load],
-	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
-	[AC_CHECK_FUNC([dlopen],
-	      [lt_cv_dlopen="dlopen"],
-	  [AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
-	    [AC_CHECK_LIB([svld], [dlopen],
-		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
-	      [AC_CHECK_LIB([dld], [dld_link],
-		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
-	      ])
-	    ])
-	  ])
-	])
-      ])
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
-    enable_dlopen=no
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
-
-    save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
-
-    save_LIBS="$LIBS"
-    LIBS="$lt_cv_dlopen_libs $LIBS"
-
-    AC_CACHE_CHECK([whether a program can dlopen itself],
-	  lt_cv_dlopen_self, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
-	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
-    ])
-
-    if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
-	  lt_cv_dlopen_self_static, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
-	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
-      ])
-    fi
-
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=unknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=unknown ;;
-  esac
-fi
-_LT_DECL([dlopen_support], [enable_dlopen], [0],
-	 [Whether dlopen is supported])
-_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
-	 [Whether dlopen of programs is supported])
-_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
-	 [Whether dlopen of statically linked programs is supported])
-])# LT_SYS_DLOPEN_SELF
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
-
-
-# _LT_COMPILER_C_O([TAGNAME])
-# ---------------------------
-# Check to see if options -c and -o are simultaneously supported by compiler.
-# This macro does not hard code the compiler like AC_PROG_CC_C_O.
-m4_defun([_LT_COMPILER_C_O],
-[m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
-   $RM -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=$?
-   cat out/conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
-       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-     fi
-   fi
-   chmod u+w . 2>&AS_MESSAGE_LOG_FD
-   $RM conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
-   $RM out/* && rmdir out
-   cd ..
-   $RM -r conftest
-   $RM conftest*
-])
-_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
-	[Does compiler simultaneously support -c and -o options?])
-])# _LT_COMPILER_C_O
-
-
-# _LT_COMPILER_FILE_LOCKS([TAGNAME])
-# ----------------------------------
-# Check to see if we can do hard links to lock some files if needed
-m4_defun([_LT_COMPILER_FILE_LOCKS],
-[m4_require([_LT_ENABLE_LOCK])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_COMPILER_C_O([$1])
-
-hard_links="nottested"
-if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
-  # do not overwrite the value of need_locks provided by the user
-  AC_MSG_CHECKING([if we can lock with hard links])
-  hard_links=yes
-  $RM conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=no
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  AC_MSG_RESULT([$hard_links])
-  if test "$hard_links" = no; then
-    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
-    need_locks=warn
-  fi
-else
-  need_locks=no
-fi
-_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
-])# _LT_COMPILER_FILE_LOCKS
-
-
-# _LT_CHECK_OBJDIR
-# ----------------
-m4_defun([_LT_CHECK_OBJDIR],
-[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
-[rm -f .libs 2>/dev/null
-mkdir .libs 2>/dev/null
-if test -d .libs; then
-  lt_cv_objdir=.libs
-else
-  # MS-DOS does not allow filenames that begin with a dot.
-  lt_cv_objdir=_libs
-fi
-rmdir .libs 2>/dev/null])
-objdir=$lt_cv_objdir
-_LT_DECL([], [objdir], [0],
-         [The name of the directory that contains temporary libtool files])dnl
-m4_pattern_allow([LT_OBJDIR])dnl
-AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
-  [Define to the sub-directory in which libtool stores uninstalled libraries.])
-])# _LT_CHECK_OBJDIR
-
-
-# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
-# --------------------------------------
-# Check hardcoding attributes.
-m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
-[AC_MSG_CHECKING([how to hardcode library paths into programs])
-_LT_TAGVAR(hardcode_action, $1)=
-if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
-   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
-   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
-
-  # We can hardcode non-existent directories.
-  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
-     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
-    # Linking always hardcodes the temporary library directory.
-    _LT_TAGVAR(hardcode_action, $1)=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    _LT_TAGVAR(hardcode_action, $1)=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  _LT_TAGVAR(hardcode_action, $1)=unsupported
-fi
-AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
-
-if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
-   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
-_LT_TAGDECL([], [hardcode_action], [0],
-    [How to hardcode a shared library path into an executable])
-])# _LT_LINKER_HARDCODE_LIBPATH
-
-
-# _LT_CMD_STRIPLIB
-# ----------------
-m4_defun([_LT_CMD_STRIPLIB],
-[m4_require([_LT_DECL_EGREP])
-striplib=
-old_striplib=
-AC_MSG_CHECKING([whether stripping libraries is possible])
-if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
-  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  AC_MSG_RESULT([yes])
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-  darwin*)
-    if test -n "$STRIP" ; then
-      striplib="$STRIP -x"
-      old_striplib="$STRIP -S"
-      AC_MSG_RESULT([yes])
-    else
-      AC_MSG_RESULT([no])
-    fi
-    ;;
-  *)
-    AC_MSG_RESULT([no])
-    ;;
-  esac
-fi
-_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
-_LT_DECL([], [striplib], [1])
-])# _LT_CMD_STRIPLIB
-
-
-# _LT_SYS_DYNAMIC_LINKER([TAG])
-# -----------------------------
-# PORTME Fill in your ld.so characteristics
-m4_defun([_LT_SYS_DYNAMIC_LINKER],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_OBJDUMP])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_CHECK_SHELL_FEATURES])dnl
-AC_MSG_CHECKING([dynamic linker characteristics])
-m4_if([$1],
-	[], [
-if test "$GCC" = yes; then
-  case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) lt_awk_arg="/^libraries:/" ;;
-  esac
-  case $host_os in
-    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
-    *) lt_sed_strip_eq="s,=/,/,g" ;;
-  esac
-  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
-  case $lt_search_path_spec in
-  *\;*)
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that should
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
-    ;;
-  *)
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
-    ;;
-  esac
-  # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
-  lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
-  for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
-      test -d "$lt_sys_path" && \
-	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
-    fi
-  done
-  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
-  for (lt_i = NF; lt_i > 0; lt_i--) {
-    if ($lt_i != "" && $lt_i != ".") {
-      if ($lt_i == "..") {
-        lt_count++;
-      } else {
-        if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
-        } else {
-          lt_count--;
-        }
-      }
-    }
-  }
-  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
-  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
-}'`
-  # AWK program above erroneously prepends '/' to C:/dos/paths
-  # for these hosts.
-  case $host_os in
-    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
-      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
-  esac
-  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
-else
-  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
-fi])
-library_names_spec=
-libname_spec='lib$name'
-soname_spec=
-shrext_cmds=".so"
-postinstall_cmds=
-postuninstall_cmds=
-finish_cmds=
-finish_eval=
-shlibpath_var=
-shlibpath_overrides_runpath=unknown
-version_type=none
-dynamic_linker="$host_os ld.so"
-sys_lib_dlsearch_path_spec="/lib /usr/lib"
-need_lib_prefix=unknown
-hardcode_into_libs=no
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=unknown
-
-case $host_os in
-aix3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
-  shlibpath_var=LIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
-  ;;
-
-aix[[4-9]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
-    # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=LD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[[01]] | aix4.[[01]].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
-	:
-      else
-	can_build_shared=no
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=LIBPATH
-  fi
-  ;;
-
-amigaos*)
-  case $host_cpu in
-  powerpc)
-    # Since July 2007 AmigaOS4 officially supports .so libraries.
-    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    ;;
-  m68k)
-    library_names_spec='$libname.ixlibrary $libname.a'
-    # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
-    ;;
-  esac
-  ;;
-
-beos*)
-  library_names_spec='${libname}${shared_ext}'
-  dynamic_linker="$host_os ld.so"
-  shlibpath_var=LIBRARY_PATH
-  ;;
-
-bsdi[[45]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32* | cegcc*)
-  version_type=windows
-  shrext_cmds=".dll"
-  need_version=no
-  need_lib_prefix=no
-
-  case $GCC,$cc_basename in
-  yes,*)
-    # gcc
-    library_names_spec='$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname~
-      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
-        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
-      fi'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-m4_if([$1], [],[
-      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
-      ;;
-    mingw* | cegcc*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    dynamic_linker='Win32 ld.exe'
-    ;;
-
-  *,cl*)
-    # Native MSVC
-    libname_spec='$name'
-    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-    library_names_spec='${libname}.dll.lib'
-
-    case $build_os in
-    mingw*)
-      sys_lib_search_path_spec=
-      lt_save_ifs=$IFS
-      IFS=';'
-      for lt_path in $LIB
-      do
-        IFS=$lt_save_ifs
-        # Let DOS variable expansion print the short 8.3 style file name.
-        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
-        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
-      done
-      IFS=$lt_save_ifs
-      # Convert to MSYS style.
-      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
-      ;;
-    cygwin*)
-      # Convert to unix form, then to dos form, then back to unix form
-      # but this time dos style (no spaces!) so that the unix form looks
-      # like /cygdrive/c/PROGRA~1:/cygdr...
-      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
-      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
-      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      ;;
-    *)
-      sys_lib_search_path_spec="$LIB"
-      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
-        # It is most probably a Windows format PATH.
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      # FIXME: find the short name or the path components, as spaces are
-      # common. (e.g. "Program Files" -> "PROGRA~1")
-      ;;
-    esac
-
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-    dynamic_linker='Win32 link.exe'
-    ;;
-
-  *)
-    # Assume MSVC wrapper
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
-    dynamic_linker='Win32 ld.exe'
-    ;;
-  esac
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=PATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker="$host_os dyld"
-  version_type=darwin
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=yes
-  shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
-m4_if([$1], [],[
-  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
-  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[[23]].*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
-  version_type=freebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=no
-      need_lib_prefix=no
-      ;;
-    freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
-      need_version=yes
-      ;;
-  esac
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_os in
-  freebsd2.*)
-    shlibpath_overrides_runpath=yes
-    ;;
-  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
-  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=no
-    hardcode_into_libs=yes
-    ;;
-  *) # from 4.6 on, and DragonFly
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-haiku*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
-  hardcode_into_libs=yes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  hppa*64*)
-    shrext_cmds='.sl'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
-  postinstall_cmds='chmod 555 $lib'
-  # or fails outright, so override atomically:
-  install_override_mode=555
-  ;;
-
-interix[[3-9]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux # correct to gnu/linux during the next big refactor
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-
-  # Some binutils ld are patched to set DT_RUNPATH
-  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
-    [lt_cv_shlibpath_overrides_runpath=no
-    save_LDFLAGS=$LDFLAGS
-    save_libdir=$libdir
-    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
-	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
-	 [lt_cv_shlibpath_overrides_runpath=yes])])
-    LDFLAGS=$save_LDFLAGS
-    libdir=$save_libdir
-    ])
-  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
-
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
-
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
-
-newsos6)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
-
-*nto* | *qnx*)
-  version_type=qnx
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='ldqnx.so'
-  ;;
-
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[[89]] | openbsd2.[[89]].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
-
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
-
-rdos*)
-  dynamic_linker=no
-  ;;
-
-solaris*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
-tpf*)
-  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-uts4*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=no
-  ;;
-esac
-AC_MSG_RESULT([$dynamic_linker])
-test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
-fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
-fi
-
-_LT_DECL([], [variables_saved_for_relink], [1],
-    [Variables whose values should be saved in libtool wrapper scripts and
-    restored at link time])
-_LT_DECL([], [need_lib_prefix], [0],
-    [Do we need the "lib" prefix for modules?])
-_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
-_LT_DECL([], [version_type], [0], [Library versioning type])
-_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
-_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
-_LT_DECL([], [shlibpath_overrides_runpath], [0],
-    [Is shlibpath searched before the hard-coded library search path?])
-_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
-_LT_DECL([], [library_names_spec], [1],
-    [[List of archive names.  First name is the real one, the rest are links.
-    The last name is the one that the linker finds with -lNAME]])
-_LT_DECL([], [soname_spec], [1],
-    [[The coded name of the library, if different from the real name]])
-_LT_DECL([], [install_override_mode], [1],
-    [Permission mode override for installation of shared libraries])
-_LT_DECL([], [postinstall_cmds], [2],
-    [Command to use after installation of a shared archive])
-_LT_DECL([], [postuninstall_cmds], [2],
-    [Command to use after uninstallation of a shared archive])
-_LT_DECL([], [finish_cmds], [2],
-    [Commands used to finish a libtool library installation in a directory])
-_LT_DECL([], [finish_eval], [1],
-    [[As "finish_cmds", except a single script fragment to be evaled but
-    not shown]])
-_LT_DECL([], [hardcode_into_libs], [0],
-    [Whether we should hardcode library paths into libraries])
-_LT_DECL([], [sys_lib_search_path_spec], [2],
-    [Compile-time system search path for libraries])
-_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
-    [Run-time system search path for libraries])
-])# _LT_SYS_DYNAMIC_LINKER
-
-
-# _LT_PATH_TOOL_PREFIX(TOOL)
-# --------------------------
-# find a file program which can recognize shared library
-AC_DEFUN([_LT_PATH_TOOL_PREFIX],
-[m4_require([_LT_DECL_EGREP])dnl
-AC_MSG_CHECKING([for $1])
-AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
-[case $MAGIC_CMD in
-[[\\/*] |  ?:[\\/]*])
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-dnl $ac_dummy forces splitting on constant user-supplied paths.
-dnl POSIX.2 word splitting is done only on the output of word expansions,
-dnl not every word.  This closes a longstanding sh security hole.
-  ac_dummy="m4_if([$2], , $PATH, [$2])"
-  for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$1; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<_LT_EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-_LT_EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
-  ;;
-esac])
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  AC_MSG_RESULT($MAGIC_CMD)
-else
-  AC_MSG_RESULT(no)
-fi
-_LT_DECL([], [MAGIC_CMD], [0],
-	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
-])# _LT_PATH_TOOL_PREFIX
-
-# Old name:
-AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
-
-
-# _LT_PATH_MAGIC
-# --------------
-# find a file program which can recognize a shared library
-m4_defun([_LT_PATH_MAGIC],
-[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
-  else
-    MAGIC_CMD=:
-  fi
-fi
-])# _LT_PATH_MAGIC
-
-
-# LT_PATH_LD
-# ----------
-# find the pathname to the GNU or non-GNU linker
-AC_DEFUN([LT_PATH_LD],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
-
-AC_ARG_WITH([gnu-ld],
-    [AS_HELP_STRING([--with-gnu-ld],
-	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
-    [test "$withval" = no || with_gnu_ld=yes],
-    [with_gnu_ld=no])dnl
-
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  AC_MSG_CHECKING([for ld used by $CC])
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [[\\/]]* | ?:[[\\/]]*)
-      re_direlt='/[[^/]][[^/]]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
-      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD="$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  AC_MSG_CHECKING([for GNU ld])
-else
-  AC_MSG_CHECKING([for non-GNU ld])
-fi
-AC_CACHE_VAL(lt_cv_path_LD,
-[if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
-	;;
-      *)
-	test "$with_gnu_ld" != yes && break
-	;;
-      esac
-    fi
-  done
-  IFS="$lt_save_ifs"
-else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi])
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  AC_MSG_RESULT($LD)
-else
-  AC_MSG_RESULT(no)
-fi
-test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
-_LT_PATH_LD_GNU
-AC_SUBST([LD])
-
-_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
-])# LT_PATH_LD
-
-# Old names:
-AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
-AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_LD], [])
-dnl AC_DEFUN([AC_PROG_LD], [])
-
-
-# _LT_PATH_LD_GNU
-#- --------------
-m4_defun([_LT_PATH_LD_GNU],
-[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
-[# I'd rather use --version here, but apparently some GNU lds only accept -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=yes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=no
-  ;;
-esac])
-with_gnu_ld=$lt_cv_prog_gnu_ld
-])# _LT_PATH_LD_GNU
-
-
-# _LT_CMD_RELOAD
-# --------------
-# find reload flag for linker
-#   -- PORTME Some linkers may need a different reload flag.
-m4_defun([_LT_CMD_RELOAD],
-[AC_CACHE_CHECK([for $LD option to reload object files],
-  lt_cv_ld_reload_flag,
-  [lt_cv_ld_reload_flag='-r'])
-reload_flag=$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=" $reload_flag" ;;
-esac
-reload_cmds='$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
-      reload_cmds=false
-    fi
-    ;;
-  darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
-    else
-      reload_cmds='$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
-_LT_TAGDECL([], [reload_cmds], [2])dnl
-])# _LT_CMD_RELOAD
-
-
-# _LT_CHECK_MAGIC_METHOD
-# ----------------------
-# how to check for library dependencies
-#  -- PORTME fill in with the dynamic library characteristics
-m4_defun([_LT_CHECK_MAGIC_METHOD],
-[m4_require([_LT_DECL_EGREP])
-m4_require([_LT_DECL_OBJDUMP])
-AC_CACHE_CHECK([how to recognize dependent libraries],
-lt_cv_deplibs_check_method,
-[lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix[[4-9]]*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-bsdi[[45]]*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
-
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd='func_win32_libid'
-  ;;
-
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdump',
-  # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
-    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-    lt_cv_file_magic_cmd='func_win32_libid'
-  else
-    # Keep this pattern in sync with the one in func_win32_libid.
-    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
-    lt_cv_file_magic_cmd='$OBJDUMP -f'
-  fi
-  ;;
-
-cegcc*)
-  # use the weaker test based on 'objdump'. See mingw*.
-  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-freebsd* | dragonfly*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
-
-gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-haiku*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
-    ;;
-  hppa*64*)
-    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
-    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
-    ;;
-  *)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
-    lt_cv_file_magic_test_file=/usr/lib/libc.sl
-    ;;
-  esac
-  ;;
-
-interix[[3-9]]*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=32-bit;;
-  *-n32|*"-n32 ") libmagic=N32;;
-  *-64|*"-64 ") libmagic=64-bit;;
-  *) libmagic=never-match;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-netbsd*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
-  fi
-  ;;
-
-newos6*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
-
-*nto* | *qnx*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  fi
-  ;;
-
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-rdos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
-    lt_cv_file_magic_test_file=/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  esac
-  ;;
-
-tpf*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-esac
-])
-
-file_magic_glob=
-want_nocaseglob=no
-if test "$build" = "$host"; then
-  case $host_os in
-  mingw* | pw32*)
-    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
-      want_nocaseglob=yes
-    else
-      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
-    fi
-    ;;
-  esac
-fi
-
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=unknown
-
-_LT_DECL([], [deplibs_check_method], [1],
-    [Method to check whether dependent libraries are shared objects])
-_LT_DECL([], [file_magic_cmd], [1],
-    [Command to use when deplibs_check_method = "file_magic"])
-_LT_DECL([], [file_magic_glob], [1],
-    [How to find potential files when deplibs_check_method = "file_magic"])
-_LT_DECL([], [want_nocaseglob], [1],
-    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
-])# _LT_CHECK_MAGIC_METHOD
-
-
-# LT_PATH_NM
-# ----------
-# find the pathname to a BSD- or MS-compatible name lister
-AC_DEFUN([LT_PATH_NM],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
-[if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
-  done
-  : ${lt_cv_path_NM=no}
-fi])
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
-else
-  # Didn't find any BSD compatible name lister, look for dumpbin.
-  if test -n "$DUMPBIN"; then :
-    # Let the user override the test.
-  else
-    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
-    *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
-      ;;
-    *)
-      DUMPBIN=:
-      ;;
-    esac
-  fi
-  AC_SUBST([DUMPBIN])
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
-  fi
-fi
-test -z "$NM" && NM=nm
-AC_SUBST([NM])
-_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
-
-AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
-  [lt_cv_nm_interface="BSD nm"
-  echo "int some_variable = 0;" > conftest.$ac_ext
-  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
-  (eval "$ac_compile" 2>conftest.err)
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
-  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
-  cat conftest.out >&AS_MESSAGE_LOG_FD
-  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
-    lt_cv_nm_interface="MS dumpbin"
-  fi
-  rm -f conftest*])
-])# LT_PATH_NM
-
-# Old names:
-AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
-AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_NM], [])
-dnl AC_DEFUN([AC_PROG_NM], [])
-
-# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
-# --------------------------------
-# how to determine the name of the shared library
-# associated with a specific link library.
-#  -- PORTME fill in with the dynamic library characteristics
-m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
-[m4_require([_LT_DECL_EGREP])
-m4_require([_LT_DECL_OBJDUMP])
-m4_require([_LT_DECL_DLLTOOL])
-AC_CACHE_CHECK([how to associate runtime and link libraries],
-lt_cv_sharedlib_from_linklib_cmd,
-[lt_cv_sharedlib_from_linklib_cmd='unknown'
-
-case $host_os in
-cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
-  case `$DLLTOOL --help 2>&1` in
-  *--identify-strict*)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
-    ;;
-  *)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
-    ;;
-  esac
-  ;;
-*)
-  # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
-  ;;
-esac
-])
-sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
-test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
-
-_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
-    [Command to associate shared and link libraries])
-])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
-
-
-# _LT_PATH_MANIFEST_TOOL
-# ----------------------
-# locate the manifest tool
-m4_defun([_LT_PATH_MANIFEST_TOOL],
-[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
-test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
-AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
-  [lt_cv_path_mainfest_tool=no
-  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
-  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
-    lt_cv_path_mainfest_tool=yes
-  fi
-  rm -f conftest*])
-if test "x$lt_cv_path_mainfest_tool" != xyes; then
-  MANIFEST_TOOL=:
-fi
-_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
-])# _LT_PATH_MANIFEST_TOOL
-
-
-# LT_LIB_M
-# --------
-# check for math library
-AC_DEFUN([LT_LIB_M],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-LIBM=
-case $host in
-*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
-  # These system don't have libm, or don't need it
-  ;;
-*-ncr-sysv4.3*)
-  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
-  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
-  ;;
-*)
-  AC_CHECK_LIB(m, cos, LIBM="-lm")
-  ;;
-esac
-AC_SUBST([LIBM])
-])# LT_LIB_M
-
-# Old name:
-AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_CHECK_LIBM], [])
-
-
-# _LT_COMPILER_NO_RTTI([TAGNAME])
-# -------------------------------
-m4_defun([_LT_COMPILER_NO_RTTI],
-[m4_require([_LT_TAG_COMPILER])dnl
-
-_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-
-if test "$GCC" = yes; then
-  case $cc_basename in
-  nvcc*)
-    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
-  *)
-    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
-  esac
-
-  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
-    lt_cv_prog_compiler_rtti_exceptions,
-    [-fno-rtti -fno-exceptions], [],
-    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
-fi
-_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
-	[Compiler flag to turn off builtin functions])
-])# _LT_COMPILER_NO_RTTI
-
-
-# _LT_CMD_GLOBAL_SYMBOLS
-# ----------------------
-m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_PROG_AWK])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-
-# Check for command to grab the raw symbol name followed by C symbol from nm.
-AC_MSG_CHECKING([command to parse $NM output from $compiler object])
-AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
-[
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode='[[BCDEGRST]]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode='[[BCDT]]'
-  ;;
-cygwin* | mingw* | pw32* | cegcc*)
-  symcode='[[ABCDGISTW]]'
-  ;;
-hpux*)
-  if test "$host_cpu" = ia64; then
-    symcode='[[ABCDEGRST]]'
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode='[[BCDEGRST]]'
-  ;;
-osf*)
-  symcode='[[BCDEGQRST]]'
-  ;;
-solaris*)
-  symcode='[[BDRT]]'
-  ;;
-sco3.2v5*)
-  symcode='[[DT]]'
-  ;;
-sysv4.2uw2*)
-  symcode='[[DT]]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[[ABDT]]'
-  ;;
-sysv4)
-  symcode='[[DFNSTU]]'
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode='[[ABCDGIRSTW]]' ;;
-esac
-
-# Transform an extracted symbol line into a proper C declaration.
-# Some systems (esp. on ia64) link data and code symbols differently,
-# so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-
-# Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
-
-# Handle CRLF in mingw tool chain
-opt_cr=
-case $build_os in
-mingw*)
-  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# Try without a prefix underscore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
-  symxfrm="\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
-    # Also find C++ and __fastcall symbols from MSVC++,
-    # which start with @ or ?.
-    lt_cv_sys_global_symbol_pipe="$AWK ['"\
-"     {last_section=section; section=\$ 3};"\
-"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
-"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
-"     \$ 0!~/External *\|/{next};"\
-"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
-"     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
-"     ' prfx=^$ac_symprfx]"
-  else
-    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-  fi
-  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
-
-  # Check to see that the pipe works correctly.
-  pipe_works=no
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<_LT_EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(void);
-void nm_test_func(void){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var='a';nm_test_func();return(0);}
-_LT_EOF
-
-  if AC_TRY_EVAL(ac_compile); then
-    # Now try to grab the symbols.
-    nlist=conftest.nm
-    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
-	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<_LT_EOF > conftest.$ac_ext
-/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
-   relocations are performed -- see ld's documentation on pseudo-relocs.  */
-# define LT@&t@_DLSYM_CONST
-#elif defined(__osf__)
-/* This system does not cope well with relocations in const data.  */
-# define LT@&t@_DLSYM_CONST
-#else
-# define LT@&t@_DLSYM_CONST const
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-_LT_EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
-
-	  cat <<_LT_EOF >> conftest.$ac_ext
-
-/* The mapping between symbol names and symbols.  */
-LT@&t@_DLSYM_CONST struct {
-  const char *name;
-  void       *address;
-}
-lt__PROGRAM__LTX_preloaded_symbols[[]] =
-{
-  { "@PROGRAM@", (void *) 0 },
-_LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
-	  cat <<\_LT_EOF >> conftest.$ac_ext
-  {0, (void *) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt__PROGRAM__LTX_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-_LT_EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_globsym_save_LIBS=$LIBS
-	  lt_globsym_save_CFLAGS=$CFLAGS
-	  LIBS="conftstm.$ac_objext"
-	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
-	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
-	    pipe_works=yes
-	  fi
-	  LIBS=$lt_globsym_save_LIBS
-	  CFLAGS=$lt_globsym_save_CFLAGS
-	else
-	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
-    fi
-  else
-    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
-    cat conftest.$ac_ext >&5
-  fi
-  rm -rf conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=
-  fi
-done
-])
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
-  AC_MSG_RESULT(failed)
-else
-  AC_MSG_RESULT(ok)
-fi
-
-# Response file support.
-if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-  nm_file_list_spec='@'
-elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
-  nm_file_list_spec='@'
-fi
-
-_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
-    [Take the output of nm and produce a listing of raw symbols and C names])
-_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
-    [Transform the output of nm in a proper C declaration])
-_LT_DECL([global_symbol_to_c_name_address],
-    [lt_cv_sys_global_symbol_to_c_name_address], [1],
-    [Transform the output of nm in a C name address pair])
-_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
-    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
-    [Transform the output of nm in a C name address pair when lib prefix is needed])
-_LT_DECL([], [nm_file_list_spec], [1],
-    [Specify filename containing input files for $NM])
-]) # _LT_CMD_GLOBAL_SYMBOLS
-
-
-# _LT_COMPILER_PIC([TAGNAME])
-# ---------------------------
-m4_defun([_LT_COMPILER_PIC],
-[m4_require([_LT_TAG_COMPILER])dnl
-_LT_TAGVAR(lt_prog_compiler_wl, $1)=
-_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-_LT_TAGVAR(lt_prog_compiler_static, $1)=
-
-m4_if([$1], [CXX], [
-  # C++ specific cases for pic, static, wl, etc.
-  if test "$GXX" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-    aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-    mingw* | cygwin* | os2* | pw32* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-    *djgpp*)
-      # DJGPP does not support shared libraries at all
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-      ;;
-    haiku*)
-      # PIC is the default for Haiku.
-      # The "-static" flag exists, but is broken.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)=
-      ;;
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-    *qnx* | *nto*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-  else
-    case $host_os in
-      aix[[4-9]]*)
-	# All AIX code is PIC.
-	if test "$host_cpu" = ia64; then
-	  # AIX 5 now supports IA64 processor
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	else
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-	fi
-	;;
-      chorus*)
-	case $cc_basename in
-	cxch68*)
-	  # Green Hills C++ Compiler
-	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
-	  ;;
-	esac
-	;;
-      mingw* | cygwin* | os2* | pw32* | cegcc*)
-	# This hack is so that the source file can tell whether it is being
-	# built for inclusion in a dll (and should export symbols for example).
-	m4_if([$1], [GCJ], [],
-	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-	;;
-      dgux*)
-	case $cc_basename in
-	  ec++*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  ghcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      freebsd* | dragonfly*)
-	# FreeBSD uses GNU C++
-	;;
-      hpux9* | hpux10* | hpux11*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    if test "$host_cpu" != ia64; then
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	    fi
-	    ;;
-	  aCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    case $host_cpu in
-	    hppa*64*|ia64*)
-	      # +Z the default
-	      ;;
-	    *)
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	      ;;
-	    esac
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
-      irix5* | irix6* | nonstopux*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    # CC pic flag -KPIC is the default.
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      linux* | k*bsd*-gnu | kopensolaris*-gnu)
-	case $cc_basename in
-	  KCC*)
-	    # KAI C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    ;;
-	  ecpc* )
-	    # old Intel C++ for x86_64 which still supported -KPIC.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  icpc* )
-	    # Intel C++, used to be incompatible with GCC.
-	    # ICC 10 doesn't accept -KPIC any more.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  pgCC* | pgcpp*)
-	    # Portland Group C++ compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  cxx*)
-	    # Compaq C++
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
-	    # IBM XL 8.0, 9.0 on PPC and BlueGene
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-      lynxos*)
-	;;
-      m88k*)
-	;;
-      mvs*)
-	case $cc_basename in
-	  cxx*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      netbsd*)
-	;;
-      *qnx* | *nto*)
-        # QNX uses GNU C++, but need to define -shared option too, otherwise
-        # it will coredump.
-        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-        ;;
-      osf3* | osf4* | osf5*)
-	case $cc_basename in
-	  KCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    ;;
-	  RCC*)
-	    # Rational C++ 2.4.1
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  cxx*)
-	    # Digital/Compaq C++
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      psos*)
-	;;
-      solaris*)
-	case $cc_basename in
-	  CC* | sunCC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	    ;;
-	  gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sunos4*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.x
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  lcc*)
-	    # Lucid
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	esac
-	;;
-      tandem*)
-	case $cc_basename in
-	  NCC*)
-	    # NonStop-UX NCC 3.20
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      vxworks*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-	;;
-    esac
-  fi
-],
-[
-  if test "$GCC" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-
-    haiku*)
-      # PIC is the default for Haiku.
-      # The "-static" flag exists, but is broken.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)=
-      ;;
-
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared libraries
-      # on systems that don't support them.
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      enable_shared=no
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-
-    case $cc_basename in
-    nvcc*) # Cuda Compiler Driver 2.2
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
-      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
-        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
-      fi
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compiler.
-    case $host_os in
-    aix*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      else
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC (with -KPIC) is the default.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    linux* | k*bsd*-gnu | kopensolaris*-gnu)
-      case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
-      ecc*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # icc used to be incompatible with GCC.
-      # ICC 10 doesn't accept -KPIC any more.
-      icc* | ifort*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # Lahey Fortran 8.1.
-      lf95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
-	;;
-      nagfor*)
-	# NAG Fortran compiler
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	;;
-      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-        ;;
-      ccc*)
-        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-        # All Alpha code is PIC.
-        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-        ;;
-      xl* | bgxl* | bgf* | mpixl*)
-	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	;;
-      *)
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
-	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
-	  ;;
-	*Sun\ F* | *Sun*Fortran*)
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	  ;;
-	*Sun\ C*)
-	  # Sun C 5.9
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  ;;
-        *Intel*\ [[CF]]*Compiler*)
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	  ;;
-	*Portland\ Group*)
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  ;;
-	esac
-	;;
-      esac
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    osf3* | osf4* | osf5*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # All OSF/1 code is PIC.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    rdos*)
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    unicos*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-    esac
-  fi
-])
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-    ;;
-  *)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
-    ;;
-esac
-
-AC_CACHE_CHECK([for $compiler option to produce PIC],
-  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
-  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
-_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
-  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
-    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
-    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
-    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
-     "" | " "*) ;;
-     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
-     esac],
-    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
-fi
-_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
-	[Additional compiler flags for building library objects])
-
-_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
-	[How to pass a linker flag through the compiler])
-#
-# Check to make sure the static flag actually works.
-#
-wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
-_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
-  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
-  $lt_tmp_static_flag,
-  [],
-  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
-_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
-	[Compiler flag to prevent dynamic linking])
-])# _LT_COMPILER_PIC
-
-
-# _LT_LINKER_SHLIBS([TAGNAME])
-# ----------------------------
-# See if the linker supports building shared libraries.
-m4_defun([_LT_LINKER_SHLIBS],
-[AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-m4_require([_LT_PATH_MANIFEST_TOOL])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-m4_if([$1], [CXX], [
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
-  case $host_os in
-  aix[[4-9]]*)
-    # If we're using GNU nm, then we don't want the "-C" option.
-    # -C means demangle to AIX nm, but means don't demangle with GNU nm
-    # Also, AIX nm treats weak defined symbols like other global defined
-    # symbols, whereas GNU nm marks them as "W".
-    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-    else
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-    fi
-    ;;
-  pw32*)
-    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
-    ;;
-  cygwin* | mingw* | cegcc*)
-    case $cc_basename in
-    cl*)
-      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
-      ;;
-    *)
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
-      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
-      ;;
-    esac
-    ;;
-  *)
-    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-    ;;
-  esac
-], [
-  runpath_var=
-  _LT_TAGVAR(allow_undefined_flag, $1)=
-  _LT_TAGVAR(always_export_symbols, $1)=no
-  _LT_TAGVAR(archive_cmds, $1)=
-  _LT_TAGVAR(archive_expsym_cmds, $1)=
-  _LT_TAGVAR(compiler_needs_object, $1)=no
-  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  _LT_TAGVAR(hardcode_automatic, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
-  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-  _LT_TAGVAR(hardcode_libdir_separator, $1)=
-  _LT_TAGVAR(hardcode_minus_L, $1)=no
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  _LT_TAGVAR(inherit_rpath, $1)=no
-  _LT_TAGVAR(link_all_deplibs, $1)=unknown
-  _LT_TAGVAR(module_cmds, $1)=
-  _LT_TAGVAR(module_expsym_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
-  _LT_TAGVAR(thread_safe_flag_spec, $1)=
-  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-  # include_expsyms should be a list of space-separated symbols to be *always*
-  # included in the symbol list
-  _LT_TAGVAR(include_expsyms, $1)=
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  # Exclude shared library initialization/finalization symbols.
-dnl Note also adjust exclude_expsyms for C++ above.
-  extract_expsyms_cmds=
-
-  case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" != yes; then
-      with_gnu_ld=no
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
-  openbsd*)
-    with_gnu_ld=no
-    ;;
-  esac
-
-  _LT_TAGVAR(ld_shlibs, $1)=yes
-
-  # On some targets, GNU ld is compatible enough with the native linker
-  # that we're better off using the native interface for both.
-  lt_use_gnu_ld_interface=no
-  if test "$with_gnu_ld" = yes; then
-    case $host_os in
-      aix*)
-	# The AIX port of GNU ld has always aspired to compatibility
-	# with the native linker.  However, as the warning in the GNU ld
-	# block says, versions before 2.19.5* couldn't really create working
-	# shared libraries, regardless of the interface used.
-	case `$LD -v 2>&1` in
-	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
-	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
-	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
-	  *)
-	    lt_use_gnu_ld_interface=yes
-	    ;;
-	esac
-	;;
-      *)
-	lt_use_gnu_ld_interface=yes
-	;;
-    esac
-  fi
-
-  if test "$lt_use_gnu_ld_interface" = yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-    else
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>&1` in
-      *GNU\ gold*) supports_anon_versioning=yes ;;
-      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix[[3-9]]*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.19, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to install binutils
-*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
-*** You will then need to restart the configuration process.
-
-_LT_EOF
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-      # as there is no search path for DLLs.
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(always_export_symbols, $1)=no
-      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
-      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
-
-      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    haiku*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    interix[[3-9]]*)
-      _LT_TAGVAR(hardcode_direct, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
-      tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
-	case $cc_basename in
-	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
-	esac
-      fi
-      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
-      then
-	tmp_addflag=' $pic_flag'
-	tmp_sharedflag='-shared'
-	case $cc_basename,$host_cpu in
-        pgcc*)				# Portland Group C compiler
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95* | pgfortran*)
-					# Portland Group f77 and f90 compilers
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	lf95*)				# Lahey Fortran 8.1
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-	  tmp_sharedflag='--shared' ;;
-	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
-	  tmp_sharedflag='-qmkshrobj'
-	  tmp_addflag= ;;
-	nvcc*)	# Cuda Compiler Driver 2.2
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  _LT_TAGVAR(compiler_needs_object, $1)=yes
-	  ;;
-	esac
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ C*)			# Sun C 5.9
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  _LT_TAGVAR(compiler_needs_object, $1)=yes
-	  tmp_sharedflag='-G' ;;
-	*Sun\ F*)			# Sun Fortran 8.3
-	  tmp_sharedflag='-G' ;;
-	esac
-	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-        if test "x$supports_anon_versioning" = xyes; then
-          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	    echo "local: *; };" >> $output_objdir/$libname.ver~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-        fi
-
-	case $cc_basename in
-	xlf* | bgf* | bgxlf* | mpixlf*)
-	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
-	  if test "x$supports_anon_versioning" = xyes; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
-	  fi
-	  ;;
-	esac
-      else
-        _LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
-	wlarc=
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  # For security reasons, it is highly recommended that you always
-	  # use absolute paths for naming shared libraries, and exclude the
-	  # DT_RUNPATH tag from executables and libraries.  But doing so
-	  # requires that you compile everything twice, which is a pain.
-	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-	  else
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-    esac
-
-    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
-      runpath_var=
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	_LT_TAGVAR(hardcode_direct, $1)=unsupported
-      fi
-      ;;
-
-    aix[[4-9]]*)
-      if test "$host_cpu" = ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=no
-	exp_sym_flag='-Bexport'
-	no_entry_flag=""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	# Also, AIX nm treats weak defined symbols like other global
-	# defined symbols, whereas GNU nm marks them as "W".
-	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	else
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=no
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
-	    aix_use_runtimelinking=yes
-	    break
-	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag='-bexport'
-	no_entry_flag='-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      _LT_TAGVAR(archive_cmds, $1)=''
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-      if test "$GCC" = yes; then
-	case $host_os in aix4.[[012]]|aix4.[[012]].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	  # We have reworked collect2
-	  :
-	  else
-	  # We have old collect2
-	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-	  ;;
-	esac
-	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" = ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
-	  else
-	    shared_flag='${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to export.
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      if test "$aix_use_runtimelinking" = yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-        # Determine the default libpath from the value encoded in an
-        # empty executable.
-        _LT_SYS_MODULE_PATH_AIX([$1])
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-      else
-	if test "$host_cpu" = ia64; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an
-	 # empty executable.
-	 _LT_SYS_MODULE_PATH_AIX([$1])
-	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	  if test "$with_gnu_ld" = yes; then
-	    # We only use this code for GNU lds that support --whole-archive.
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	  else
-	    # Exported symbols can be pulled into shared objects from archives
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
-	  fi
-	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    bsdi[[45]]*)
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      case $cc_basename in
-      cl*)
-	# Native MSVC
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	_LT_TAGVAR(always_export_symbols, $1)=yes
-	_LT_TAGVAR(file_list_spec, $1)='@'
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	  else
-	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	  fi~
-	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	  linknames='
-	# The linker will not automatically build a static lib if we build a DLL.
-	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
-	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
-	# Don't use ranlib
-	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
-	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	  lt_tool_outputfile="@TOOL_OUTPUT@"~
-	  case $lt_outputfile in
-	    *.exe|*.EXE) ;;
-	    *)
-	      lt_outputfile="$lt_outputfile.exe"
-	      lt_tool_outputfile="$lt_tool_outputfile.exe"
-	      ;;
-	  esac~
-	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	    $RM "$lt_outputfile.manifest";
-	  fi'
-	;;
-      *)
-	# Assume MSVC wrapper
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
-	# The linker will automatically build a .lib file if we build a DLL.
-	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	# FIXME: Should let the user specify the lib program.
-	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
-	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	;;
-      esac
-      ;;
-
-    darwin* | rhapsody*)
-      _LT_DARWIN_LINKER_FEATURES($1)
-      ;;
-
-    dgux*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
-    # support.  Future versions do this automatically, but an explicit c++rt0.o
-    # does not break anything, and helps significantly (at the cost of a little
-    # extra space).
-    freebsd2.2*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2.*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | dragonfly*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    hpux9*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
-	_LT_TAGVAR(hardcode_direct, $1)=yes
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	_LT_TAGVAR(hardcode_minus_L, $1)=yes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	m4_if($1, [], [
-	  # Older versions of the 11.00 compiler do not understand -b yet
-	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
-	  _LT_LINKER_OPTION([if $CC understands -b],
-	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
-	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
-	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
-	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  ;;
-	*)
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	# Try to use the -exported_symbol ld option, if it does not
-	# work, assume that -exports_file does not work either and
-	# implicitly export all symbols.
-	# This should be the same for all languages, so no per-tag cache variable.
-	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
-	  [lt_cv_irix_exported_symbol],
-	  [save_LDFLAGS="$LDFLAGS"
-	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
-	   AC_LINK_IFELSE(
-	     [AC_LANG_SOURCE(
-	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
-			      [C++], [[int foo (void) { return 0; }]],
-			      [Fortran 77], [[
-      subroutine foo
-      end]],
-			      [Fortran], [[
-      subroutine foo
-      end]])])],
-	      [lt_cv_irix_exported_symbol=yes],
-	      [lt_cv_irix_exported_symbol=no])
-           LDFLAGS="$save_LDFLAGS"])
-	if test "$lt_cv_irix_exported_symbol" = yes; then
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
-	fi
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(inherit_rpath, $1)=yes
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *nto* | *qnx*)
-      ;;
-
-    openbsd*)
-      if test -f /usr/libexec/ld.so; then
-	_LT_TAGVAR(hardcode_direct, $1)=yes
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	else
-	  case $host_os in
-	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
-	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	     ;;
-	   *)
-	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	     ;;
-	  esac
-	fi
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    os2*)
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      else
-	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-      else
-	case `$CC -V 2>&1` in
-	*"Compilers 5.0"*)
-	  wlarc=''
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
-	  ;;
-	*)
-	  wlarc='${wl}'
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-	  ;;
-	esac
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      case $host_os in
-      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-      *)
-	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
-	# but is careful enough not to reorder.
-	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-	else
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	fi
-	;;
-      esac
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" = xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-        ;;
-	motorola)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
-	;;
-      esac
-      runpath_var='LD_RUN_PATH'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4.3*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	runpath_var=LD_RUN_PATH
-	hardcode_runpath_var=yes
-	_LT_TAGVAR(ld_shlibs, $1)=yes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      _LT_TAGVAR(ld_shlibs, $1)=no
-      ;;
-    esac
-
-    if test x$host_vendor = xsni; then
-      case $host in
-      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
-	;;
-      esac
-    fi
-  fi
-])
-AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
-
-_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
-_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
-_LT_DECL([], [extract_expsyms_cmds], [2],
-    [The commands to extract the exported symbol list from a shared archive])
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
-x|xyes)
-  # Assume -lc should be added
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
-    case $_LT_TAGVAR(archive_cmds, $1) in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
-	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
-	[$RM conftest*
-	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
-	  soname=conftest
-	  lib=conftest
-	  libobjs=conftest.$ac_objext
-	  deplibs=
-	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
-	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
-	  compiler_flags=-v
-	  linker_flags=-v
-	  verstring=
-	  output_objdir=.
-	  libname=conftest
-	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
-	  _LT_TAGVAR(allow_undefined_flag, $1)=
-	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
-	  then
-	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	  else
-	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  fi
-	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
-	else
-	  cat conftest.err 1>&5
-	fi
-	$RM conftest*
-	])
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
-    [Whether or not to add -lc for building shared libraries])
-_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
-    [enable_shared_with_static_runtimes], [0],
-    [Whether or not to disallow shared libs when runtime libs are static])
-_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
-    [Compiler flag to allow reflexive dlopens])
-_LT_TAGDECL([], [whole_archive_flag_spec], [1],
-    [Compiler flag to generate shared objects directly from archives])
-_LT_TAGDECL([], [compiler_needs_object], [1],
-    [Whether the compiler copes with passing no objects directly])
-_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
-    [Create an old-style archive from a shared archive])
-_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
-    [Create a temporary old-style archive to link instead of a shared archive])
-_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
-_LT_TAGDECL([], [archive_expsym_cmds], [2])
-_LT_TAGDECL([], [module_cmds], [2],
-    [Commands used to build a loadable module if different from building
-    a shared archive.])
-_LT_TAGDECL([], [module_expsym_cmds], [2])
-_LT_TAGDECL([], [with_gnu_ld], [1],
-    [Whether we are building with GNU ld or not])
-_LT_TAGDECL([], [allow_undefined_flag], [1],
-    [Flag that allows shared libraries with undefined symbols to be built])
-_LT_TAGDECL([], [no_undefined_flag], [1],
-    [Flag that enforces no undefined symbols])
-_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
-    [Flag to hardcode $libdir into a binary during linking.
-    This must work even if $libdir does not exist])
-_LT_TAGDECL([], [hardcode_libdir_separator], [1],
-    [Whether we need a single "-rpath" flag with a separated argument])
-_LT_TAGDECL([], [hardcode_direct], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary])
-_LT_TAGDECL([], [hardcode_direct_absolute], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary and the resulting library dependency is
-    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
-    library is relocated])
-_LT_TAGDECL([], [hardcode_minus_L], [0],
-    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
-    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_automatic], [0],
-    [Set to "yes" if building a shared library automatically hardcodes DIR
-    into the library and all subsequent libraries and executables linked
-    against it])
-_LT_TAGDECL([], [inherit_rpath], [0],
-    [Set to yes if linker adds runtime paths of dependent libraries
-    to runtime path list])
-_LT_TAGDECL([], [link_all_deplibs], [0],
-    [Whether libtool must link a program against all its dependency libraries])
-_LT_TAGDECL([], [always_export_symbols], [0],
-    [Set to "yes" if exported symbols are required])
-_LT_TAGDECL([], [export_symbols_cmds], [2],
-    [The commands to list exported symbols])
-_LT_TAGDECL([], [exclude_expsyms], [1],
-    [Symbols that should not be listed in the preloaded symbols])
-_LT_TAGDECL([], [include_expsyms], [1],
-    [Symbols that must always be exported])
-_LT_TAGDECL([], [prelink_cmds], [2],
-    [Commands necessary for linking programs (against libraries) with templates])
-_LT_TAGDECL([], [postlink_cmds], [2],
-    [Commands necessary for finishing linking programs])
-_LT_TAGDECL([], [file_list_spec], [1],
-    [Specify filename containing input files])
-dnl FIXME: Not yet implemented
-dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
-dnl    [Compiler flag to generate thread safe objects])
-])# _LT_LINKER_SHLIBS
-
-
-# _LT_LANG_C_CONFIG([TAG])
-# ------------------------
-# Ensure that the configuration variables for a C compiler are suitably
-# defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_C_CONFIG],
-[m4_require([_LT_DECL_EGREP])dnl
-lt_save_CC="$CC"
-AC_LANG_PUSH(C)
-
-# Source file extension for C test sources.
-ac_ext=c
-
-# Object file extension for compiled C test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="int some_variable = 0;"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='int main(){return(0);}'
-
-_LT_TAG_COMPILER
-# Save the default compiler, since it gets overwritten when the other
-# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
-compiler_DEFAULT=$CC
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_SYS_DYNAMIC_LINKER($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-  LT_SYS_DLOPEN_SELF
-  _LT_CMD_STRIPLIB
-
-  # Report which library types will actually be built
-  AC_MSG_CHECKING([if libtool supports shared libraries])
-  AC_MSG_RESULT([$can_build_shared])
-
-  AC_MSG_CHECKING([whether to build shared libraries])
-  test "$can_build_shared" = "no" && enable_shared=no
-
-  # On AIX, shared libraries and static libraries use the same namespace, and
-  # are all built from PIC.
-  case $host_os in
-  aix3*)
-    test "$enable_shared" = yes && enable_static=no
-    if test -n "$RANLIB"; then
-      archive_cmds="$archive_cmds~\$RANLIB \$lib"
-      postinstall_cmds='$RANLIB $lib'
-    fi
-    ;;
-
-  aix[[4-9]]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
-    fi
-    ;;
-  esac
-  AC_MSG_RESULT([$enable_shared])
-
-  AC_MSG_CHECKING([whether to build static libraries])
-  # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
-  AC_MSG_RESULT([$enable_static])
-
-  _LT_CONFIG($1)
-fi
-AC_LANG_POP
-CC="$lt_save_CC"
-])# _LT_LANG_C_CONFIG
-
-
-# _LT_LANG_CXX_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for a C++ compiler are suitably
-# defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_CXX_CONFIG],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_PATH_MANIFEST_TOOL])dnl
-if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
-    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" != "Xg++"))) ; then
-  AC_PROG_CXXCPP
-else
-  _lt_caught_CXX_error=yes
-fi
-
-AC_LANG_PUSH(C++)
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(compiler_needs_object, $1)=no
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for C++ test sources.
-ac_ext=cpp
-
-# Object file extension for compiled C++ test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the CXX compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_caught_CXX_error" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="int some_variable = 0;"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC=$CC
-  lt_save_CFLAGS=$CFLAGS
-  lt_save_LD=$LD
-  lt_save_GCC=$GCC
-  GCC=$GXX
-  lt_save_with_gnu_ld=$with_gnu_ld
-  lt_save_path_LD=$lt_cv_path_LD
-  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
-    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
-  else
-    $as_unset lt_cv_prog_gnu_ld
-  fi
-  if test -n "${lt_cv_path_LDCXX+set}"; then
-    lt_cv_path_LD=$lt_cv_path_LDCXX
-  else
-    $as_unset lt_cv_path_LD
-  fi
-  test -z "${LDCXX+set}" || LD=$LDCXX
-  CC=${CXX-"c++"}
-  CFLAGS=$CXXFLAGS
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    # We don't want -fno-exception when compiling C++ code, so set the
-    # no_builtin_flag separately
-    if test "$GXX" = yes; then
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
-    else
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-    fi
-
-    if test "$GXX" = yes; then
-      # Set up default GNU C++ configuration
-
-      LT_PATH_LD
-
-      # Check if GNU C++ uses GNU ld as the underlying linker, since the
-      # archiving commands below assume that GNU ld is being used.
-      if test "$with_gnu_ld" = yes; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-        # If archive_cmds runs LD, not CC, wlarc should be empty
-        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
-        #     investigate it a little bit more. (MM)
-        wlarc='${wl}'
-
-        # ancient GNU ld didn't support --whole-archive et. al.
-        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
-	  $GREP 'no-whole-archive' > /dev/null; then
-          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-        else
-          _LT_TAGVAR(whole_archive_flag_spec, $1)=
-        fi
-      else
-        with_gnu_ld=no
-        wlarc=
-
-        # A generic and very simple default shared library creation
-        # command for GNU C++ for the case where it uses the native
-        # linker, instead of GNU ld.  If possible, this setting should
-        # overridden to take advantage of the native linker features on
-        # the platform it is being used on.
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-      fi
-
-      # Commands to make compiler produce verbose output that lists
-      # what "hidden" libraries, object files and flags are used when
-      # linking a shared library.
-      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-
-    else
-      GXX=no
-      with_gnu_ld=no
-      wlarc=
-    fi
-
-    # PORTME: fill in a description of your system's C++ link characteristics
-    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-    _LT_TAGVAR(ld_shlibs, $1)=yes
-    case $host_os in
-      aix3*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-      aix[[4-9]]*)
-        if test "$host_cpu" = ia64; then
-          # On IA64, the linker does run time linking by default, so we don't
-          # have to do anything special.
-          aix_use_runtimelinking=no
-          exp_sym_flag='-Bexport'
-          no_entry_flag=""
-        else
-          aix_use_runtimelinking=no
-
-          # Test if we are trying to use run time linking or normal
-          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-          # need to do runtime linking.
-          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	    for ld_flag in $LDFLAGS; do
-	      case $ld_flag in
-	      *-brtl*)
-	        aix_use_runtimelinking=yes
-	        break
-	        ;;
-	      esac
-	    done
-	    ;;
-          esac
-
-          exp_sym_flag='-bexport'
-          no_entry_flag='-bnoentry'
-        fi
-
-        # When large executables or shared objects are built, AIX ld can
-        # have problems creating the table of contents.  If linking a library
-        # or program results in "error TOC overflow" add -mminimal-toc to
-        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-        _LT_TAGVAR(archive_cmds, $1)=''
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-        _LT_TAGVAR(link_all_deplibs, $1)=yes
-        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-        if test "$GXX" = yes; then
-          case $host_os in aix4.[[012]]|aix4.[[012]].*)
-          # We only want to do this on AIX 4.2 and lower, the check
-          # below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	    # We have reworked collect2
-	    :
-	  else
-	    # We have old collect2
-	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	    # It fails to find uninstalled libraries when the uninstalled
-	    # path is not listed in the libpath.  Setting hardcode_minus_L
-	    # to unsupported forces relinking
-	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-          esac
-          shared_flag='-shared'
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag="$shared_flag "'${wl}-G'
-	  fi
-        else
-          # not using gcc
-          if test "$host_cpu" = ia64; then
-	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	  # chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-          else
-	    if test "$aix_use_runtimelinking" = yes; then
-	      shared_flag='${wl}-G'
-	    else
-	      shared_flag='${wl}-bM:SRE'
-	    fi
-          fi
-        fi
-
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-        # It seems that -bexpall does not export symbols beginning with
-        # underscore (_), so it is better to generate a list of symbols to
-	# export.
-        _LT_TAGVAR(always_export_symbols, $1)=yes
-        if test "$aix_use_runtimelinking" = yes; then
-          # Warning - without using the other runtime loading flags (-brtl),
-          # -berok will link without error, but may produce a broken library.
-          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-          # Determine the default libpath from the value encoded in an empty
-          # executable.
-          _LT_SYS_MODULE_PATH_AIX([$1])
-          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-        else
-          if test "$host_cpu" = ia64; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-          else
-	    # Determine the default libpath from the value encoded in an
-	    # empty executable.
-	    _LT_SYS_MODULE_PATH_AIX([$1])
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	    # Warning - without using the other run time loading flags,
-	    # -berok will link without error, but may produce a broken library.
-	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	    if test "$with_gnu_ld" = yes; then
-	      # We only use this code for GNU lds that support --whole-archive.
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	    else
-	      # Exported symbols can be pulled into shared objects from archives
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
-	    fi
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	    # This is similar to how AIX traditionally builds its shared
-	    # libraries.
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-          fi
-        fi
-        ;;
-
-      beos*)
-	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	  # support --undefined.  This deserves some investigation.  FIXME
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      chorus*)
-        case $cc_basename in
-          *)
-	  # FIXME: insert proper C++ library support
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	  ;;
-        esac
-        ;;
-
-      cygwin* | mingw* | pw32* | cegcc*)
-	case $GXX,$cc_basename in
-	,cl* | no,cl*)
-	  # Native MSVC
-	  # hardcode_libdir_flag_spec is actually meaningless, as there is
-	  # no search path for DLLs.
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  _LT_TAGVAR(always_export_symbols, $1)=yes
-	  _LT_TAGVAR(file_list_spec, $1)='@'
-	  # Tell ltmain to make .lib files, not .a files.
-	  libext=lib
-	  # Tell ltmain to make .dll files, not .so files.
-	  shrext_cmds=".dll"
-	  # FIXME: Setting linknames here is a bad hack.
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	    else
-	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	    fi~
-	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	    linknames='
-	  # The linker will not automatically build a static lib if we build a DLL.
-	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	  # Don't use ranlib
-	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
-	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	    lt_tool_outputfile="@TOOL_OUTPUT@"~
-	    case $lt_outputfile in
-	      *.exe|*.EXE) ;;
-	      *)
-		lt_outputfile="$lt_outputfile.exe"
-		lt_tool_outputfile="$lt_tool_outputfile.exe"
-		;;
-	    esac~
-	    func_to_tool_file "$lt_outputfile"~
-	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	      $RM "$lt_outputfile.manifest";
-	    fi'
-	  ;;
-	*)
-	  # g++
-	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-	  # as there is no search path for DLLs.
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  _LT_TAGVAR(always_export_symbols, $1)=no
-	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-
-	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	    # If the export-symbols file already is a .def file (1st line
-	    # is EXPORTS), use it as is; otherwise, prepend...
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      cp $export_symbols $output_objdir/$soname.def;
-	    else
-	      echo EXPORTS > $output_objdir/$soname.def;
-	      cat $export_symbols >> $output_objdir/$soname.def;
-	    fi~
-	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	  else
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	  ;;
-	esac
-	;;
-      darwin* | rhapsody*)
-        _LT_DARWIN_LINKER_FEATURES($1)
-	;;
-
-      dgux*)
-        case $cc_basename in
-          ec++*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          ghcx*)
-	    # Green Hills C++ Compiler
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      freebsd2.*)
-        # C++ shared libraries reported to be fairly broken before
-	# switch to ELF
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      freebsd-elf*)
-        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-        ;;
-
-      freebsd* | dragonfly*)
-        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
-        # conventions
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-        ;;
-
-      gnu*)
-        ;;
-
-      haiku*)
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(link_all_deplibs, $1)=yes
-        ;;
-
-      hpux9*)
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-				             # but as the default
-				             # location of the library.
-
-        case $cc_basename in
-          CC*)
-            # FIXME: insert proper C++ library support
-            _LT_TAGVAR(ld_shlibs, $1)=no
-            ;;
-          aCC*)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-            # Commands to make compiler produce verbose output that lists
-            # what "hidden" libraries, object files and flags are used when
-            # linking a shared library.
-            #
-            # There doesn't appear to be a way to prevent this compiler from
-            # explicitly linking system object files so we need to strip them
-            # from the output so that they don't get included in the library
-            # dependencies.
-            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-            ;;
-          *)
-            if test "$GXX" = yes; then
-              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-            else
-              # FIXME: insert proper C++ library support
-              _LT_TAGVAR(ld_shlibs, $1)=no
-            fi
-            ;;
-        esac
-        ;;
-
-      hpux10*|hpux11*)
-        if test $with_gnu_ld = no; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-          case $host_cpu in
-            hppa*64*|ia64*)
-              ;;
-            *)
-	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-              ;;
-          esac
-        fi
-        case $host_cpu in
-          hppa*64*|ia64*)
-            _LT_TAGVAR(hardcode_direct, $1)=no
-            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-            ;;
-          *)
-            _LT_TAGVAR(hardcode_direct, $1)=yes
-            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-					         # but as the default
-					         # location of the library.
-            ;;
-        esac
-
-        case $cc_basename in
-          CC*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          aCC*)
-	    case $host_cpu in
-	      hppa*64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      ia64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      *)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	    esac
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-	    ;;
-          *)
-	    if test "$GXX" = yes; then
-	      if test $with_gnu_ld = no; then
-	        case $host_cpu in
-	          hppa*64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	          ia64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	          *)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	        esac
-	      fi
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      interix[[3-9]]*)
-	_LT_TAGVAR(hardcode_direct, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-	# Instead, shared libraries are loaded at an image base (0x10000000 by
-	# default) and relocated if they conflict, which is a slow very memory
-	# consuming and fragmenting process.  To avoid this, we pick a random,
-	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	;;
-      irix5* | irix6*)
-        case $cc_basename in
-          CC*)
-	    # SGI C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    if test "$GXX" = yes; then
-	      if test "$with_gnu_ld" = no; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	      else
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
-	      fi
-	    fi
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-	    ;;
-        esac
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(inherit_rpath, $1)=yes
-        ;;
-
-      linux* | k*bsd*-gnu | kopensolaris*-gnu)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
-	    ;;
-	  icpc* | ecpc* )
-	    # Intel C++
-	    with_gnu_ld=yes
-	    # version 8.0 and above of icpc choke on multiply defined symbols
-	    # if we add $predep_objects and $postdep_objects, however 7.1 and
-	    # earlier do not add the objects themselves.
-	    case `$CC -V 2>&1` in
-	      *"Version 7."*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	      *)  # Version 8.0 or newer
-	        tmp_idyn=
-	        case $host_cpu in
-		  ia64*) tmp_idyn=' -i_dynamic';;
-		esac
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	    esac
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	    ;;
-          pgCC* | pgcpp*)
-            # Portland Group C++ compiler
-	    case `$CC -V` in
-	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
-	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
-		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
-	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
-		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
-		$RANLIB $oldlib'
-	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
-	      ;;
-	    *) # Version 6 and above use weak symbols
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
-	      ;;
-	    esac
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-            ;;
-	  cxx*)
-	    # Compaq C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
-
-	    runpath_var=LD_RUN_PATH
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
-	    ;;
-	  xl* | mpixl* | bgxl*)
-	    # IBM XL 8.0 on PPC, with GNU ld
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    if test "x$supports_anon_versioning" = xyes; then
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-		echo "local: *; };" >> $output_objdir/$libname.ver~
-		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	    fi
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	      _LT_TAGVAR(compiler_needs_object, $1)=yes
-
-	      # Not sure whether something based on
-	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
-	      # would be better.
-	      output_verbose_link_cmd='func_echo_all'
-
-	      # Archives containing C++ object files must be created using
-	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	      # necessary to make sure instantiated templates are included
-	      # in the archive.
-	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-
-      lynxos*)
-        # FIXME: insert proper C++ library support
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      m88k*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      mvs*)
-        case $cc_basename in
-          cxx*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	  *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	esac
-	;;
-
-      netbsd*)
-        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
-	  wlarc=
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	fi
-	# Workaround some broken pre-1.5 toolchains
-	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
-	;;
-
-      *nto* | *qnx*)
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-	;;
-
-      openbsd2*)
-        # C++ shared libraries are fairly broken
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      openbsd*)
-	if test -f /usr/libexec/ld.so; then
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-	  fi
-	  output_verbose_link_cmd=func_echo_all
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      osf3* | osf4* | osf5*)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Archives containing C++ object files must be created using
-	    # the KAI C++ compiler.
-	    case $host in
-	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
-	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
-	    esac
-	    ;;
-          RCC*)
-	    # Rational C++ 2.4.1
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          cxx*)
-	    case $host in
-	      osf3*)
-	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-		;;
-	      *)
-	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
-	          echo "-hidden">> $lib.exp~
-	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
-	          $RM $lib.exp'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-		;;
-	    esac
-
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-	    ;;
-	  *)
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	      case $host in
-	        osf3*)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-		  ;;
-	        *)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-		  ;;
-	      esac
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	      # Commands to make compiler produce verbose output that lists
-	      # what "hidden" libraries, object files and flags are used when
-	      # linking a shared library.
-	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      psos*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      sunos4*)
-        case $cc_basename in
-          CC*)
-	    # Sun C++ 4.x
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          lcc*)
-	    # Lucid
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      solaris*)
-        case $cc_basename in
-          CC* | sunCC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
-	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	    case $host_os in
-	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-	      *)
-		# The compiler driver will combine and reorder linker options,
-		# but understands `-z linker_flag'.
-	        # Supported since Solaris 2.6 (maybe 2.5.1?)
-		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	        ;;
-	    esac
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-
-	    output_verbose_link_cmd='func_echo_all'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	    ;;
-          gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-
-	    # The C++ compiler must be used to create the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    # GNU C++ compiler with Solaris linker
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
-	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	        # Commands to make compiler produce verbose output that lists
-	        # what "hidden" libraries, object files and flags are used when
-	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-	      else
-	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
-	        # platform.
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	        # Commands to make compiler produce verbose output that lists
-	        # what "hidden" libraries, object files and flags are used when
-	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-	      fi
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
-	      case $host_os in
-		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-		*)
-		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-		  ;;
-	      esac
-	    fi
-	    ;;
-        esac
-        ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      case $cc_basename in
-        CC*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-      esac
-      ;;
-
-      sysv5* | sco3.2v5* | sco5v6*)
-	# Note: We can NOT use -z defs as we might desire, because we do not
-	# link with -lc, and that would cause any symbols used from libc to
-	# always be unresolved, which means just about no library would
-	# ever link correctly.  If we're not using GNU ld we use -z text
-	# though, which does catch some bad symbols but isn't as heavy-handed
-	# as -z defs.
-	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-	_LT_TAGVAR(link_all_deplibs, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-	runpath_var='LD_RUN_PATH'
-
-	case $cc_basename in
-          CC*)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
-	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
-	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
-	      '"$_LT_TAGVAR(reload_cmds, $1)"
-	    ;;
-	  *)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    ;;
-	esac
-      ;;
-
-      tandem*)
-        case $cc_basename in
-          NCC*)
-	    # NonStop-UX NCC 3.20
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      vxworks*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      *)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-    esac
-
-    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-    _LT_TAGVAR(GCC, $1)="$GXX"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  CC=$lt_save_CC
-  CFLAGS=$lt_save_CFLAGS
-  LDCXX=$LD
-  LD=$lt_save_LD
-  GCC=$lt_save_GCC
-  with_gnu_ld=$lt_save_with_gnu_ld
-  lt_cv_path_LDCXX=$lt_cv_path_LD
-  lt_cv_path_LD=$lt_save_path_LD
-  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
-  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
-fi # test "$_lt_caught_CXX_error" != yes
-
-AC_LANG_POP
-])# _LT_LANG_CXX_CONFIG
-
-
-# _LT_FUNC_STRIPNAME_CNF
-# ----------------------
-# func_stripname_cnf prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-#
-# This function is identical to the (non-XSI) version of func_stripname,
-# except this one can be used by m4 code that may be executed by configure,
-# rather than the libtool script.
-m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
-AC_REQUIRE([_LT_DECL_SED])
-AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
-func_stripname_cnf ()
-{
-  case ${2} in
-  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
-  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
-  esac
-} # func_stripname_cnf
-])# _LT_FUNC_STRIPNAME_CNF
-
-# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
-# ---------------------------------
-# Figure out "hidden" library dependencies from verbose
-# compiler output when linking a shared library.
-# Parse the compiler output and extract the necessary
-# objects, libraries and library flags.
-m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
-# Dependencies to place before and after the object being linked:
-_LT_TAGVAR(predep_objects, $1)=
-_LT_TAGVAR(postdep_objects, $1)=
-_LT_TAGVAR(predeps, $1)=
-_LT_TAGVAR(postdeps, $1)=
-_LT_TAGVAR(compiler_lib_search_path, $1)=
-
-dnl we can't use the lt_simple_compile_test_code here,
-dnl because it contains code intended for an executable,
-dnl not a library.  It's possible we should let each
-dnl tag define a new lt_????_link_test_code variable,
-dnl but it's only used here...
-m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
-int a;
-void foo (void) { a = 0; }
-_LT_EOF
-], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
-class Foo
-{
-public:
-  Foo (void) { a = 0; }
-private:
-  int a;
-};
-_LT_EOF
-], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer*4 a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
-public class foo {
-  private int a;
-  public void bar (void) {
-    a = 0;
-  }
-};
-_LT_EOF
-], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
-package foo
-func foo() {
-}
-_LT_EOF
-])
-
-_lt_libdeps_save_CFLAGS=$CFLAGS
-case "$CC $CFLAGS " in #(
-*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
-*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
-*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
-esac
-
-dnl Parse the compiler output and extract the necessary
-dnl objects, libraries and library flags.
-if AC_TRY_EVAL(ac_compile); then
-  # Parse the compiler output and extract the necessary
-  # objects, libraries and library flags.
-
-  # Sentinel used to keep track of whether or not we are before
-  # the conftest object file.
-  pre_test_object_deps_done=no
-
-  for p in `eval "$output_verbose_link_cmd"`; do
-    case ${prev}${p} in
-
-    -L* | -R* | -l*)
-       # Some compilers place space between "-{L,R}" and the path.
-       # Remove the space.
-       if test $p = "-L" ||
-          test $p = "-R"; then
-	 prev=$p
-	 continue
-       fi
-
-       # Expand the sysroot to ease extracting the directories later.
-       if test -z "$prev"; then
-         case $p in
-         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
-         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
-         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
-         esac
-       fi
-       case $p in
-       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
-       esac
-       if test "$pre_test_object_deps_done" = no; then
-	 case ${prev} in
-	 -L | -R)
-	   # Internal compiler library paths should come after those
-	   # provided the user.  The postdeps already come after the
-	   # user supplied libs so there is no need to process them.
-	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
-	   else
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
-	   fi
-	   ;;
-	 # The "-l" case would never come before the object being
-	 # linked, so don't bother handling this case.
-	 esac
-       else
-	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
-	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
-	 else
-	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
-	 fi
-       fi
-       prev=
-       ;;
-
-    *.lto.$objext) ;; # Ignore GCC LTO objects
-    *.$objext)
-       # This assumes that the test object file only shows up
-       # once in the compiler output.
-       if test "$p" = "conftest.$objext"; then
-	 pre_test_object_deps_done=yes
-	 continue
-       fi
-
-       if test "$pre_test_object_deps_done" = no; then
-	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
-	   _LT_TAGVAR(predep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
-	 fi
-       else
-	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
-	   _LT_TAGVAR(postdep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
-	 fi
-       fi
-       ;;
-
-    *) ;; # Ignore the rest.
-
-    esac
-  done
-
-  # Clean up.
-  rm -f a.out a.exe
-else
-  echo "libtool.m4: error: problem compiling $1 test program"
-fi
-
-$RM -f confest.$objext
-CFLAGS=$_lt_libdeps_save_CFLAGS
-
-# PORTME: override above test on systems where it is broken
-m4_if([$1], [CXX],
-[case $host_os in
-interix[[3-9]]*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  _LT_TAGVAR(predep_objects,$1)=
-  _LT_TAGVAR(postdep_objects,$1)=
-  _LT_TAGVAR(postdeps,$1)=
-  ;;
-
-linux*)
-  case `$CC -V 2>&1 | sed 5q` in
-  *Sun\ C*)
-    # Sun C++ 5.9
-
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC* | sunCC*)
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-esac
-])
-
-case " $_LT_TAGVAR(postdeps, $1) " in
-*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
-esac
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=
-if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
-fi
-_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
-    [The directories searched by this compiler when creating a shared library])
-_LT_TAGDECL([], [predep_objects], [1],
-    [Dependencies to place before and after the objects being linked to
-    create a shared library])
-_LT_TAGDECL([], [postdep_objects], [1])
-_LT_TAGDECL([], [predeps], [1])
-_LT_TAGDECL([], [postdeps], [1])
-_LT_TAGDECL([], [compiler_lib_search_path], [1],
-    [The library search path used internally by the compiler when linking
-    a shared library])
-])# _LT_SYS_HIDDEN_LIBDEPS
-
-
-# _LT_LANG_F77_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for a Fortran 77 compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_F77_CONFIG],
-[AC_LANG_PUSH(Fortran 77)
-if test -z "$F77" || test "X$F77" = "Xno"; then
-  _lt_disable_F77=yes
-fi
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for f77 test sources.
-ac_ext=f
-
-# Object file extension for compiled f77 test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the F77 compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_F77" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
-  lt_save_GCC=$GCC
-  lt_save_CFLAGS=$CFLAGS
-  CC=${F77-"f77"}
-  CFLAGS=$FFLAGS
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-  GCC=$G77
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$G77"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC="$lt_save_CC"
-  CFLAGS="$lt_save_CFLAGS"
-fi # test "$_lt_disable_F77" != yes
-
-AC_LANG_POP
-])# _LT_LANG_F77_CONFIG
-
-
-# _LT_LANG_FC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for a Fortran compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_FC_CONFIG],
-[AC_LANG_PUSH(Fortran)
-
-if test -z "$FC" || test "X$FC" = "Xno"; then
-  _lt_disable_FC=yes
-fi
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for fc test sources.
-ac_ext=${ac_fc_srcext-f}
-
-# Object file extension for compiled fc test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the FC compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_FC" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
-  lt_save_GCC=$GCC
-  lt_save_CFLAGS=$CFLAGS
-  CC=${FC-"f95"}
-  CFLAGS=$FCFLAGS
-  compiler=$CC
-  GCC=$ac_cv_fc_compiler_gnu
-
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC=$lt_save_CC
-  CFLAGS=$lt_save_CFLAGS
-fi # test "$_lt_disable_FC" != yes
-
-AC_LANG_POP
-])# _LT_LANG_FC_CONFIG
-
-
-# _LT_LANG_GCJ_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for the GNU Java Compiler compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_GCJ_CONFIG],
-[AC_REQUIRE([LT_PROG_GCJ])dnl
-AC_LANG_SAVE
-
-# Source file extension for Java test sources.
-ac_ext=java
-
-# Object file extension for compiled Java test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="class foo {}"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=$CC
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=yes
-CC=${GCJ-"gcj"}
-CFLAGS=$GCJFLAGS
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
-_LT_CC_BASENAME([$compiler])
-
-# GCJ did not exist at the time GCC didn't implicitly link libc in.
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-
-  _LT_CONFIG($1)
-fi
-
-AC_LANG_RESTORE
-
-GCC=$lt_save_GCC
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_GCJ_CONFIG
-
-
-# _LT_LANG_GO_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for the GNU Go compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_GO_CONFIG],
-[AC_REQUIRE([LT_PROG_GO])dnl
-AC_LANG_SAVE
-
-# Source file extension for Go test sources.
-ac_ext=go
-
-# Object file extension for compiled Go test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="package main; func main() { }"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='package main; func main() { }'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=$CC
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=yes
-CC=${GOC-"gccgo"}
-CFLAGS=$GOFLAGS
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
-_LT_CC_BASENAME([$compiler])
-
-# Go did not exist at the time GCC didn't implicitly link libc in.
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-
-  _LT_CONFIG($1)
-fi
-
-AC_LANG_RESTORE
-
-GCC=$lt_save_GCC
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_GO_CONFIG
-
-
-# _LT_LANG_RC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for the Windows resource compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_RC_CONFIG],
-[AC_REQUIRE([LT_PROG_RC])dnl
-AC_LANG_SAVE
-
-# Source file extension for RC test sources.
-ac_ext=rc
-
-# Object file extension for compiled RC test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code="$lt_simple_compile_test_code"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=
-CC=${RC-"windres"}
-CFLAGS=
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
-_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-
-if test -n "$compiler"; then
-  :
-  _LT_CONFIG($1)
-fi
-
-GCC=$lt_save_GCC
-AC_LANG_RESTORE
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_RC_CONFIG
-
-
-# LT_PROG_GCJ
-# -----------
-AC_DEFUN([LT_PROG_GCJ],
-[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
-  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
-    [AC_CHECK_TOOL(GCJ, gcj,)
-      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
-      AC_SUBST(GCJFLAGS)])])[]dnl
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
-
-
-# LT_PROG_GO
-# ----------
-AC_DEFUN([LT_PROG_GO],
-[AC_CHECK_TOOL(GOC, gccgo,)
-])
-
-
-# LT_PROG_RC
-# ----------
-AC_DEFUN([LT_PROG_RC],
-[AC_CHECK_TOOL(RC, windres,)
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_RC], [])
-
-
-# _LT_DECL_EGREP
-# --------------
-# If we don't have a new enough Autoconf to choose the best grep
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_EGREP],
-[AC_REQUIRE([AC_PROG_EGREP])dnl
-AC_REQUIRE([AC_PROG_FGREP])dnl
-test -z "$GREP" && GREP=grep
-_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
-_LT_DECL([], [EGREP], [1], [An ERE matcher])
-_LT_DECL([], [FGREP], [1], [A literal string matcher])
-dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
-AC_SUBST([GREP])
-])
-
-
-# _LT_DECL_OBJDUMP
-# --------------
-# If we don't have a new enough Autoconf to choose the best objdump
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_OBJDUMP],
-[AC_CHECK_TOOL(OBJDUMP, objdump, false)
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
-AC_SUBST([OBJDUMP])
-])
-
-# _LT_DECL_DLLTOOL
-# ----------------
-# Ensure DLLTOOL variable is set.
-m4_defun([_LT_DECL_DLLTOOL],
-[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
-AC_SUBST([DLLTOOL])
-])
-
-# _LT_DECL_SED
-# ------------
-# Check for a fully-functional sed program, that truncates
-# as few characters as possible.  Prefer GNU sed if found.
-m4_defun([_LT_DECL_SED],
-[AC_PROG_SED
-test -z "$SED" && SED=sed
-Xsed="$SED -e 1s/^X//"
-_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
-_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
-    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
-])# _LT_DECL_SED
-
-m4_ifndef([AC_PROG_SED], [
-############################################################
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-############################################################
-
-m4_defun([AC_PROG_SED],
-[AC_MSG_CHECKING([for a sed that does not truncate output])
-AC_CACHE_VAL(lt_cv_path_SED,
-[# Loop through the user's path and test for sed and gsed.
-# Then use that list of sed's as ones to test for truncation.
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for lt_ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
-        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
-      fi
-    done
-  done
-done
-IFS=$as_save_IFS
-lt_ac_max=0
-lt_ac_count=0
-# Add /usr/xpg4/bin/sed as it is typically found on Solaris
-# along with /bin/sed that truncates output.
-for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
-  cat /dev/null > conftest.in
-  lt_ac_count=0
-  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
-  # Check for GNU sed and select it if it is found.
-  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
-    lt_cv_path_SED=$lt_ac_sed
-    break
-  fi
-  while true; do
-    cat conftest.in conftest.in >conftest.tmp
-    mv conftest.tmp conftest.in
-    cp conftest.in conftest.nl
-    echo >>conftest.nl
-    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
-    cmp -s conftest.out conftest.nl || break
-    # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
-    lt_ac_count=`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
-      lt_ac_max=$lt_ac_count
-      lt_cv_path_SED=$lt_ac_sed
-    fi
-  done
-done
-])
-SED=$lt_cv_path_SED
-AC_SUBST([SED])
-AC_MSG_RESULT([$SED])
-])#AC_PROG_SED
-])#m4_ifndef
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_SED], [])
-
-
-# _LT_CHECK_SHELL_FEATURES
-# ------------------------
-# Find out whether the shell is Bourne or XSI compatible,
-# or has some other useful features.
-m4_defun([_LT_CHECK_SHELL_FEATURES],
-[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-AC_MSG_RESULT([$xsi_shell])
-_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
-
-AC_MSG_CHECKING([whether the shell understands "+="])
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-AC_MSG_RESULT([$lt_shell_append])
-_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
-
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  lt_unset=unset
-else
-  lt_unset=false
-fi
-_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
-
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  lt_SP2NL='tr \040 \012'
-  lt_NL2SP='tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  lt_SP2NL='tr \100 \n'
-  lt_NL2SP='tr \r\n \100\100'
-  ;;
-esac
-_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
-_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
-])# _LT_CHECK_SHELL_FEATURES
-
-
-# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
-# ------------------------------------------------------
-# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
-# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
-m4_defun([_LT_PROG_FUNCTION_REPLACE],
-[dnl {
-sed -e '/^$1 ()$/,/^} # $1 /c\
-$1 ()\
-{\
-m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
-} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-])
-
-
-# _LT_PROG_REPLACE_SHELLFNS
-# -------------------------
-# Replace existing portable implementations of several shell functions with
-# equivalent extended shell implementations where those features are available..
-m4_defun([_LT_PROG_REPLACE_SHELLFNS],
-[if test x"$xsi_shell" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
-    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
-    # positional parameters, so assign one to ordinary parameter first.
-    func_stripname_result=${3}
-    func_stripname_result=${func_stripname_result#"${1}"}
-    func_stripname_result=${func_stripname_result%"${2}"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
-    func_split_long_opt_name=${1%%=*}
-    func_split_long_opt_arg=${1#*=}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
-    func_split_short_opt_arg=${1#??}
-    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
-    case ${1} in
-      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
-      *)    func_lo2o_result=${1} ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
-
-  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
-
-  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
-fi
-
-if test x"$lt_shell_append" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
-    func_quote_for_eval "${2}"
-dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
-    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
-
-  # Save a `func_append' function call where possible by direct use of '+='
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-else
-  # Save a `func_append' function call even when '+=' is not available
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-fi
-
-if test x"$_lt_function_replace_fail" = x":"; then
-  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
-fi
-])
-
-# _LT_PATH_CONVERSION_FUNCTIONS
-# -----------------------------
-# Determine which file name conversion functions should be used by
-# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
-# for certain cross-compile configurations and native mingw.
-m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-AC_MSG_CHECKING([how to convert $build file names to $host format])
-AC_CACHE_VAL(lt_cv_to_host_file_cmd,
-[case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
-        ;;
-    esac
-    ;;
-  *-*-cygwin* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_noop
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
-        ;;
-    esac
-    ;;
-  * ) # unhandled hosts (and "normal" native builds)
-    lt_cv_to_host_file_cmd=func_convert_file_noop
-    ;;
-esac
-])
-to_host_file_cmd=$lt_cv_to_host_file_cmd
-AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
-_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
-         [0], [convert $build file names to $host format])dnl
-
-AC_MSG_CHECKING([how to convert $build file names to toolchain format])
-AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
-[#assume ordinary cross tools, or native build.
-lt_cv_to_tool_file_cmd=func_convert_file_noop
-case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
-        ;;
-    esac
-    ;;
-esac
-])
-to_tool_file_cmd=$lt_cv_to_tool_file_cmd
-AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
-_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
-         [0], [convert $build files to toolchain format])dnl
-])# _LT_PATH_CONVERSION_FUNCTIONS
Index: sm/branches/trunk-jpl-damage/m4/ltoptions.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ltoptions.m4	(revision 13100)
+++ 	(revision )
@@ -1,384 +1,0 @@
-# Helper functions for option handling.                    -*- Autoconf -*-
-#
-#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
-#   Inc.
-#   Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 7 ltoptions.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
-
-
-# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
-# ------------------------------------------
-m4_define([_LT_MANGLE_OPTION],
-[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
-
-
-# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
-# ---------------------------------------
-# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
-# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
-# saved as a flag.
-m4_define([_LT_SET_OPTION],
-[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
-m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
-        _LT_MANGLE_DEFUN([$1], [$2]),
-    [m4_warning([Unknown $1 option `$2'])])[]dnl
-])
-
-
-# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
-# ------------------------------------------------------------
-# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
-m4_define([_LT_IF_OPTION],
-[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
-
-
-# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
-# -------------------------------------------------------
-# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
-# are set.
-m4_define([_LT_UNLESS_OPTIONS],
-[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
-		      [m4_define([$0_found])])])[]dnl
-m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
-])[]dnl
-])
-
-
-# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
-# ----------------------------------------
-# OPTION-LIST is a space-separated list of Libtool options associated
-# with MACRO-NAME.  If any OPTION has a matching handler declared with
-# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
-# the unknown option and exit.
-m4_defun([_LT_SET_OPTIONS],
-[# Set options
-m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-    [_LT_SET_OPTION([$1], _LT_Option)])
-
-m4_if([$1],[LT_INIT],[
-  dnl
-  dnl Simply set some default values (i.e off) if boolean options were not
-  dnl specified:
-  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
-  ])
-  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
-  ])
-  dnl
-  dnl If no reference was made to various pairs of opposing options, then
-  dnl we run the default mode handler for the pair.  For example, if neither
-  dnl `shared' nor `disable-shared' was passed, we enable building of shared
-  dnl archives by default:
-  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
-  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
-  		   [_LT_ENABLE_FAST_INSTALL])
-  ])
-])# _LT_SET_OPTIONS
-
-
-## --------------------------------- ##
-## Macros to handle LT_INIT options. ##
-## --------------------------------- ##
-
-# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
-# -----------------------------------------
-m4_define([_LT_MANGLE_DEFUN],
-[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
-
-
-# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
-# -----------------------------------------------
-m4_define([LT_OPTION_DEFINE],
-[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
-])# LT_OPTION_DEFINE
-
-
-# dlopen
-# ------
-LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
-])
-
-AU_DEFUN([AC_LIBTOOL_DLOPEN],
-[_LT_SET_OPTION([LT_INIT], [dlopen])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `dlopen' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
-
-
-# win32-dll
-# ---------
-# Declare package support for building win32 dll's.
-LT_OPTION_DEFINE([LT_INIT], [win32-dll],
-[enable_win32_dll=yes
-
-case $host in
-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
-  AC_CHECK_TOOL(AS, as, false)
-  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-  AC_CHECK_TOOL(OBJDUMP, objdump, false)
-  ;;
-esac
-
-test -z "$AS" && AS=as
-_LT_DECL([], [AS],      [1], [Assembler program])dnl
-
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
-
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
-])# win32-dll
-
-AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-_LT_SET_OPTION([LT_INIT], [win32-dll])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `win32-dll' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
-
-
-# _LT_ENABLE_SHARED([DEFAULT])
-# ----------------------------
-# implement the --enable-shared flag, and supports the `shared' and
-# `disable-shared' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_SHARED],
-[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([shared],
-    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
-	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
-
-    _LT_DECL([build_libtool_libs], [enable_shared], [0],
-	[Whether or not to build shared libraries])
-])# _LT_ENABLE_SHARED
-
-LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
-])
-
-AC_DEFUN([AC_DISABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], [disable-shared])
-])
-
-AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
-AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_SHARED], [])
-dnl AC_DEFUN([AM_DISABLE_SHARED], [])
-
-
-
-# _LT_ENABLE_STATIC([DEFAULT])
-# ----------------------------
-# implement the --enable-static flag, and support the `static' and
-# `disable-static' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_STATIC],
-[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([static],
-    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
-	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
-
-    _LT_DECL([build_old_libs], [enable_static], [0],
-	[Whether or not to build static libraries])
-])# _LT_ENABLE_STATIC
-
-LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
-])
-
-AC_DEFUN([AC_DISABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], [disable-static])
-])
-
-AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
-AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_STATIC], [])
-dnl AC_DEFUN([AM_DISABLE_STATIC], [])
-
-
-
-# _LT_ENABLE_FAST_INSTALL([DEFAULT])
-# ----------------------------------
-# implement the --enable-fast-install flag, and support the `fast-install'
-# and `disable-fast-install' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_FAST_INSTALL],
-[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([fast-install],
-    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
-    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=yes ;;
-    no) enable_fast_install=no ;;
-    *)
-      enable_fast_install=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_fast_install=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
-
-_LT_DECL([fast_install], [enable_fast_install], [0],
-	 [Whether or not to optimize for fast installation])dnl
-])# _LT_ENABLE_FAST_INSTALL
-
-LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
-
-# Old names:
-AU_DEFUN([AC_ENABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `fast-install' option into LT_INIT's first parameter.])
-])
-
-AU_DEFUN([AC_DISABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `disable-fast-install' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
-dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
-
-
-# _LT_WITH_PIC([MODE])
-# --------------------
-# implement the --with-pic flag, and support the `pic-only' and `no-pic'
-# LT_INIT options.
-# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
-m4_define([_LT_WITH_PIC],
-[AC_ARG_WITH([pic],
-    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
-	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
-    [lt_p=${PACKAGE-default}
-    case $withval in
-    yes|no) pic_mode=$withval ;;
-    *)
-      pic_mode=default
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for lt_pkg in $withval; do
-	IFS="$lt_save_ifs"
-	if test "X$lt_pkg" = "X$lt_p"; then
-	  pic_mode=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [pic_mode=default])
-
-test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
-
-_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
-])# _LT_WITH_PIC
-
-LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
-
-# Old name:
-AU_DEFUN([AC_LIBTOOL_PICMODE],
-[_LT_SET_OPTION([LT_INIT], [pic-only])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `pic-only' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
-
-## ----------------- ##
-## LTDL_INIT Options ##
-## ----------------- ##
-
-m4_define([_LTDL_MODE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
-		 [m4_define([_LTDL_MODE], [nonrecursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [recursive],
-		 [m4_define([_LTDL_MODE], [recursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [subproject],
-		 [m4_define([_LTDL_MODE], [subproject])])
-
-m4_define([_LTDL_TYPE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [installable],
-		 [m4_define([_LTDL_TYPE], [installable])])
-LT_OPTION_DEFINE([LTDL_INIT], [convenience],
-		 [m4_define([_LTDL_TYPE], [convenience])])
Index: sm/branches/trunk-jpl-damage/m4/ltsugar.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ltsugar.m4	(revision 13100)
+++ 	(revision )
@@ -1,123 +1,0 @@
-# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
-#
-# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
-# Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 6 ltsugar.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
-
-
-# lt_join(SEP, ARG1, [ARG2...])
-# -----------------------------
-# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
-# associated separator.
-# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
-# versions in m4sugar had bugs.
-m4_define([lt_join],
-[m4_if([$#], [1], [],
-       [$#], [2], [[$2]],
-       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
-m4_define([_lt_join],
-[m4_if([$#$2], [2], [],
-       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
-
-
-# lt_car(LIST)
-# lt_cdr(LIST)
-# ------------
-# Manipulate m4 lists.
-# These macros are necessary as long as will still need to support
-# Autoconf-2.59 which quotes differently.
-m4_define([lt_car], [[$1]])
-m4_define([lt_cdr],
-[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
-       [$#], 1, [],
-       [m4_dquote(m4_shift($@))])])
-m4_define([lt_unquote], $1)
-
-
-# lt_append(MACRO-NAME, STRING, [SEPARATOR])
-# ------------------------------------------
-# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
-# Note that neither SEPARATOR nor STRING are expanded; they are appended
-# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
-# No SEPARATOR is output if MACRO-NAME was previously undefined (different
-# than defined and empty).
-#
-# This macro is needed until we can rely on Autoconf 2.62, since earlier
-# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
-m4_define([lt_append],
-[m4_define([$1],
-	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
-
-
-
-# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
-# ----------------------------------------------------------
-# Produce a SEP delimited list of all paired combinations of elements of
-# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
-# has the form PREFIXmINFIXSUFFIXn.
-# Needed until we can rely on m4_combine added in Autoconf 2.62.
-m4_define([lt_combine],
-[m4_if(m4_eval([$# > 3]), [1],
-       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
-[[m4_foreach([_Lt_prefix], [$2],
-	     [m4_foreach([_Lt_suffix],
-		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
-	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
-
-
-# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
-# -----------------------------------------------------------------------
-# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
-# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
-m4_define([lt_if_append_uniq],
-[m4_ifdef([$1],
-	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
-		 [lt_append([$1], [$2], [$3])$4],
-		 [$5])],
-	  [lt_append([$1], [$2], [$3])$4])])
-
-
-# lt_dict_add(DICT, KEY, VALUE)
-# -----------------------------
-m4_define([lt_dict_add],
-[m4_define([$1($2)], [$3])])
-
-
-# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
-# --------------------------------------------
-m4_define([lt_dict_add_subkey],
-[m4_define([$1($2:$3)], [$4])])
-
-
-# lt_dict_fetch(DICT, KEY, [SUBKEY])
-# ----------------------------------
-m4_define([lt_dict_fetch],
-[m4_ifval([$3],
-	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
-    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
-
-
-# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
-# -----------------------------------------------------------------
-m4_define([lt_if_dict_fetch],
-[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
-	[$5],
-    [$6])])
-
-
-# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
-# --------------------------------------------------------------
-m4_define([lt_dict_filter],
-[m4_if([$5], [], [],
-  [lt_join(m4_quote(m4_default([$4], [[, ]])),
-           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
-		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
-])
Index: sm/branches/trunk-jpl-damage/m4/ltversion.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ltversion.m4	(revision 13100)
+++ 	(revision )
@@ -1,23 +1,0 @@
-# ltversion.m4 -- version numbers			-*- Autoconf -*-
-#
-#   Copyright (C) 2004 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# @configure_input@
-
-# serial 3337 ltversion.m4
-# This file is part of GNU Libtool
-
-m4_define([LT_PACKAGE_VERSION], [2.4.2])
-m4_define([LT_PACKAGE_REVISION], [1.3337])
-
-AC_DEFUN([LTVERSION_VERSION],
-[macro_version='2.4.2'
-macro_revision='1.3337'
-_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
-_LT_DECL(, macro_revision, 0)
-])
Index: sm/branches/trunk-jpl-damage/m4/lt~obsolete.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/lt~obsolete.m4	(revision 13100)
+++ 	(revision )
@@ -1,98 +1,0 @@
-# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
-#
-#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004.
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 5 lt~obsolete.m4
-
-# These exist entirely to fool aclocal when bootstrapping libtool.
-#
-# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
-# which have later been changed to m4_define as they aren't part of the
-# exported API, or moved to Autoconf or Automake where they belong.
-#
-# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
-# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
-# using a macro with the same name in our local m4/libtool.m4 it'll
-# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
-# and doesn't know about Autoconf macros at all.)
-#
-# So we provide this file, which has a silly filename so it's always
-# included after everything else.  This provides aclocal with the
-# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
-# because those macros already exist, or will be overwritten later.
-# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
-#
-# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
-# Yes, that means every name once taken will need to remain here until
-# we give up compatibility with versions before 1.7, at which point
-# we need to keep only those names which we still refer to.
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
-
-m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
-m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
-m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
-m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
-m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
-m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
-m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
-m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
-m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
-m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
-m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
-m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
-m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
-m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
-m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
-m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
-m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
-m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
-m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
-m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
-m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
-m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
-m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
-m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
-m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
-m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
-m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
-m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
-m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
-m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
-m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
-m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
-m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
-m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
-m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
-m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
-m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
-m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
-m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
-m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
-m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
-m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
-m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
-m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
-m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
-m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
-m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
-m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
-m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
-m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
-m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
-m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
-m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
Index: /issm/branches/trunk-jpl-damage/scripts/automakererun.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/automakererun.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/scripts/automakererun.sh	(revision 13101)
@@ -9,3 +9,3 @@
 
 cd $ISSM_DIR
-autoreconf -iv -I m4
+autoreconf -iv -I externalpackages/libtool/install/share/aclocal
Index: /issm/branches/trunk-jpl-damage/scripts/historyISSM.m
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/historyISSM.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/scripts/historyISSM.m	(revision 13101)
@@ -3,9 +3,6 @@
 md.mesh.numberofelements
 md=mesh(md,'DomainOutline.exp',5000);
-md=setmask(md,'','');
 md=setflowequation(md,'macayeal','all');
-md=setflowequation(md,'pattyn','all','stokes','all');
 md=solve(md,TransientSolutionEnum);
-md=solve(md,BalancedthicknessSolutionEnum);
 md=solve(md,DiagnosticSolutionEnum);
 md=loadresultsfromcluster(md);
Index: /issm/branches/trunk-jpl-damage/src/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/Makefile.am	(revision 13101)
@@ -1,2 +1,2 @@
-EXTRA_DIST =  perl  pro  py
+EXTRA_DIST =  perl pro py
 SUBDIRS = c modules m
Index: /issm/branches/trunk-jpl-damage/src/ad/todo
===================================================================
--- /issm/branches/trunk-jpl-damage/src/ad/todo	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/ad/todo	(revision 13101)
@@ -43,2 +43,8 @@
 
 Replace memcpy, realloc with x layers.  Replace all calls to malloc and free in the code.
+
+
+
+Questions: 
+set of active IssmDouble variables different from set of independent variables activated with <<=? 
+same thing dependent variables? 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 13101)
@@ -133,5 +133,5 @@
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error2_("trying to echo a NULL dataset");
+	if(this==NULL)_error_("trying to echo a NULL dataset");
 
 	_pprintLine_("DataSet echo: " << objects.size() << " objects");
@@ -150,5 +150,5 @@
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error2_("trying to echo a NULL dataset");
+	if(this==NULL)_error_("trying to echo a NULL dataset");
 
 	_pprintLine_("DataSet echo: " << objects.size() << " objects");
@@ -194,9 +194,9 @@
 
 	_assert_(this);
-	if(!sorted)_error2_("trying to binary search on a non-sorted dataset!");
+	if(!sorted)_error_("trying to binary search on a non-sorted dataset!");
 
 	/*Carry out a binary search on the sorted_ids: */
 	if(!binary_search(&id_offset,eid, sorted_ids,objects.size())){
-		_error2_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
+		_error_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
 	}
 
@@ -259,6 +259,6 @@
 	/*Only sort if we are not already sorted: */
 	if(!sorted){
-		_error2_("not implemented yet!");
-	}
-}
-/*}}}*/
+		_error_("not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 13101)
@@ -203,5 +203,5 @@
 		/*see what the first element of this partition has in stock (this is common to all partitions)*/
 		if(my_rank==minrank){
-			if(this->Size()==0) _error2_("Cannot write results because there is no element??");
+			if(this->Size()==0) _error_("Cannot write results because there is no element??");
 			Element* element=(Element*)this->GetObjectByOffset(0);
 			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
@@ -232,5 +232,5 @@
 			if(resultssizes[i]==P1Enum)      vectorsize=numberofvertices;
 			else if(resultssizes[i]==P0Enum) vectorsize=numberofelements;
-			else _error2_("Unkown result size: " << EnumToStringx(resultssizes[i]));
+			else _error_("Unkown result size: " << EnumToStringx(resultssizes[i]));
 			vector=new Vector(vectorsize);
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 13101)
@@ -57,5 +57,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -85,5 +85,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -113,5 +113,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -141,5 +141,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -213,5 +213,5 @@
 
 	/*some checks: */
-	if(!constrain_input) _error2_("input " << EnumToStringx(constrain_enum) << " could not be found!");
+	if(!constrain_input) _error_("input " << EnumToStringx(constrain_enum) << " could not be found!");
 
 	/*Apply ContrainMin: */
@@ -254,5 +254,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -275,5 +275,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -296,5 +296,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -317,5 +317,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -369,5 +369,5 @@
 	/*Make a copy of the original input: */
 	original=(Input*)this->GetInput(original_enum);
-	if(!original)_error2_("could not find input with enum: " << EnumToStringx(original_enum)); 
+	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
 	copy=(Input*)original->copy();
 
@@ -416,6 +416,6 @@
 
 	/*some checks: */
-	if(!xinput) _error2_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
-	if(!yinput) _error2_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
+	if(!xinput) _error_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
+	if(!yinput) _error_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
 
 	/*Apply AXPY: */
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp	(revision 13101)
@@ -58,11 +58,11 @@
 	options->Get(&maxtrimming,"maxtrimming",+1.e+21);
 	options->Get(&minspacing,"minspacing",0.01);
-	if(minspacing<=0) _error2_("minspacing must > 0");
+	if(minspacing<=0) _error_("minspacing must > 0");
 
 	/*Get Minimum box size*/
 	if(options->GetOption("boxlength")){
 		options->Get(&minlength,"boxlength");
-		if(minlength<=0)_error2_("boxlength should be a positive number");
-		maxdepth=int(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
+		if(minlength<=0)_error_("boxlength should be a positive number");
+		maxdepth=reCast<int,IssmDouble>(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
 	}
 	else{
@@ -383,5 +383,5 @@
 	SolverxSeq(&GinvZ, Gamma,obs,n_obs);    // Gamma^-1 Z
 #else
-	_error2_("GSL is required");
+	_error_("GSL is required");
 #endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 13101)
@@ -47,8 +47,8 @@
 
 	/*Also, check the option name*/
-	if(!in_option->name) _error2_("input option has an empty name");
-	if(strchr(in_option->name,'.')) _error2_("Option \"" << in_option->name << "\" has a protected character \".\"");
-	if(strchr(in_option->name,'[')) _error2_("Option \"" << in_option->name << "\" has a protected character \"[\"");
-	if(strchr(in_option->name,']')) _error2_("Option \"" << in_option->name << "\" has a protected character \"]\"");
+	if(!in_option->name) _error_("input option has an empty name");
+	if(strchr(in_option->name,'.')) _error_("Option \"" << in_option->name << "\" has a protected character \".\"");
+	if(strchr(in_option->name,'[')) _error_("Option \"" << in_option->name << "\" has a protected character \"[\"");
+	if(strchr(in_option->name,']')) _error_("Option \"" << in_option->name << "\" has a protected character \"]\"");
 
 	/*Finally, check that no option of the same name already exists in the dataset*/
@@ -57,5 +57,5 @@
 		option=(Option*)(*object); 
 		if (!strcmp(option->name,in_option->name)){
-			_error2_("Options \"" << in_option->name << "\" found multiple times");
+			_error_("Options \"" << in_option->name << "\" found multiple times");
 			break;
 		}
@@ -83,5 +83,5 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+		_error_("option of name \"" << name << "\" not found, and no default value has been provided");
 	}
 }
@@ -121,5 +121,5 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+		_error_("option of name \"" << name << "\" not found, and no default value has been provided");
 	}
 }
@@ -159,5 +159,5 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+		_error_("option of name \"" << name << "\" not found, and no default value has been provided");
 	}
 }
@@ -199,5 +199,5 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+		_error_("option of name \"" << name << "\" not found, and no default value has been provided");
 	}
 
@@ -264,5 +264,5 @@
 		/*Else: not supported*/
 		else{
-			_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
+			_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 		}
 	}
@@ -290,5 +290,5 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+		_error_("option of name \"" << name << "\" not found, and no default value has been provided");
 	}
 }
@@ -324,5 +324,5 @@
 				/*Else: not supported*/
 				else{
-					_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
+					_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 				}
 			}
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 13101)
@@ -65,5 +65,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -82,5 +82,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -99,5 +99,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -116,5 +116,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -133,5 +133,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -151,5 +151,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -169,5 +169,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -187,5 +187,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -205,5 +205,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -223,5 +223,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -241,5 +241,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -258,5 +258,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -276,5 +276,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -294,5 +294,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13101)
@@ -12,7 +12,5 @@
 enum definitions{
 	/*Model fields {{{1*/
-	AutodiffForwardEnum,
 	AutodiffIsautodiffEnum, 
-	AutodiffReverseEnum,
 	BalancethicknessSpcthicknessEnum,
 	BalancethicknessStabilizationEnum,
@@ -50,4 +48,5 @@
 	FlowequationElementEquationEnum,
 	FlowequationIshutterEnum,
+	FlowequationIsl1l2Enum,
 	FlowequationIsmacayealpattynEnum,
 	FlowequationIsstokesEnum,
@@ -238,9 +237,10 @@
 	/*Approximations {{{1*/
 	ApproximationEnum,
+	NoneApproximationEnum,
 	HutterApproximationEnum,
 	MacAyealApproximationEnum,
 	MacAyealPattynApproximationEnum,
 	MacAyealStokesApproximationEnum,
-	NoneApproximationEnum,
+	L1L2ApproximationEnum,
 	PattynApproximationEnum,
 	PattynStokesApproximationEnum,
@@ -286,4 +286,5 @@
 	NumericalfluxEnum,
 	ParamEnum,
+	L1L2IceFrontEnum,
 	PattynIceFrontEnum,
 	PengridEnum,
@@ -385,4 +386,6 @@
 	EnthalpyPicardEnum,
 	ThicknessAbsGradientEnum,
+	ThicknessAlongGradientEnum,
+	ThicknessAcrossGradientEnum,
 	StepResponsesEnum,
 	IntMatParamEnum,
@@ -405,8 +408,4 @@
 	StressTensoryzEnum,
 	StressTensorzzEnum,
-	IceVolumeEnum, //FIXME reposition
-	TotalSmbEnum,  //FIXME reposition
-	ThicknessAlongGradientEnum,
-	ThicknessAcrossGradientEnum,
 	/*}}}*/
 	/*Element Interpolations{{{1*/
@@ -448,4 +447,6 @@
 	MaxVzEnum,
 	MaxAbsVzEnum,
+	IceVolumeEnum,
+	TotalSmbEnum,
 	/*}}}*/
 	/*Convergence{{{1*/
Index: /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 13101)
@@ -98,5 +98,5 @@
 cat <<END >> $ISSM_DIR/src/c/modules/StringToEnumx/StringToEnumx.cpp
 	/*If we reach this point, the string provided has not been found*/
-	_error2_("Enum " << name << " not found");
+	_error_("Enum " << name << " not found");
 }
 END
@@ -107,4 +107,6 @@
 #Add header to pythonenum file{{{
 cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
+from StringToEnum import StringToEnum
+
 """
 
@@ -166,5 +168,5 @@
 	"""
 
-	return StringToEnum('$NAME')
+	return StringToEnum('$NAME')[0]
 
 END
Index: /issm/branches/trunk-jpl-damage/src/c/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/Makefile.am	(revision 13101)
@@ -1,3 +1,3 @@
-INCLUDES = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
 
 EXEEXT=$(ISSMEXT)
@@ -6,14 +6,20 @@
 lib_LIBRARIES = libISSMCore.a libISSMOverload.a
 
-#if SHARED
-#lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
-#endif
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
+endif
 if PYTHON
 lib_LIBRARIES += libISSMPython.a 
 endif
 if MATLAB
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMMatlab.la
+endif
 lib_LIBRARIES += libISSMMatlab.a 
 endif
 if MODULES
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMModules.la
+endif
 lib_LIBRARIES += libISSMModules.a 
 endif
@@ -197,4 +203,5 @@
 					./shared/Numerics/isnan.h\
 					./shared/Numerics/isnan.cpp\
+					./shared/Numerics/cubic.cpp\
 					./shared/Numerics/extrema.cpp\
 					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
@@ -384,7 +391,5 @@
 					  ./modules/Dakotax/SpawnCore.cpp\
 					  ./modules/Dakotax/DescriptorIndex.cpp\
-					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
-					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
 					  ./modules/Dakotax/SpawnCoreParallel.cpp
 #}}}
@@ -1006,13 +1011,13 @@
 libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS)
 
-#if SHARED
-#libISSM_la_SOURCES = solutions/issm.cpp
-#libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
-#
-#libISSMCore_la_SOURCES  = $(issm_sources)
-#libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
-#
-#libISSMOverload_la_SOURCES = ./shared/String/stricmp.c
-#endif
+if SHAREDLIBS
+libISSM_la_SOURCES = solutions/issm.cpp
+libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
+
+libISSMCore_la_SOURCES  = $(issm_sources)
+libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
+
+libISSMOverload_la_SOURCES = ./shared/String/stricmp.c
+endif
 
 if MODULES
@@ -1022,4 +1027,8 @@
 libISSMModules_a_SOURCES += $(kml_sources)
 libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMModules_a_LIBADD = ./libISSMCore.a
+if SHAREDLIBS
+libISSMModules_la_SOURCES = $(libISSMModules_a_SOURCES)
+endif
 endif
 
@@ -1032,6 +1041,14 @@
 libISSMMatlab_a_SOURCES = $(matlab_sources)
 libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
-endif
-
+if SHAREDLIBS
+libISSMMatlab_la_SOURCES = $(libISSMMatlab_a_SOURCES)
+endif
+endif
+
+if VERSION
+AM_LDFLAGS =
+else
+AM_LDFLAGS = -avoid-version
+endif
 #}}}
 #Overload library, to overload any non-standard symbols. {{{
Index: /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp	(revision 13101)
@@ -143,5 +143,5 @@
 		else this->sdoflist=NULL;
 	}
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp	(revision 13101)
@@ -129,5 +129,5 @@
 	}
 	if(found!=-1) analysis_counter=found;
-	else _error2_("Could not find alias for analysis_type " << EnumToStringx(configuration_type) << " in list of FemModel analyses");
+	else _error_("Could not find alias for analysis_type " << EnumToStringx(configuration_type) << " in list of FemModel analyses");
 
 	/*Now, plug analysis_counter and analysis_type inside the parameters: */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp	(revision 13101)
@@ -185,5 +185,5 @@
 			this->objects[i]=(Object*)dataset->GetObjectById(this->offsets+i,this->ids[i]); //remember the offset for later on.
 			/*check the id is correct!: */
-			if (this->objects[i]->Id()!=this->ids[i]) _error2_("wrong id: " << this->objects[i]->Id() << " vs " << this->ids[i] << "  in resolved pointer!");
+			if (this->objects[i]->Id()!=this->ids[i]) _error_("wrong id: " << this->objects[i]->Id() << " vs " << this->ids[i] << "  in resolved pointer!");
 		}
 	}
@@ -194,8 +194,8 @@
 	
 	/*first, check that we only have one T object in our object list: */
-	if (this->num!=1) _error2_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
+	if (this->num!=1) _error_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
 
 	/*check NULL: */
-	if (this->objects==NULL) _error2_("hook is not pointing to any object, objects pointer is NULL");
+	if (this->objects==NULL) _error_("hook is not pointing to any object, objects pointer is NULL");
 
 	return *objects;
@@ -246,9 +246,9 @@
 
 	/*Else, check that we are requesting a half of num*/
-	if (numindices>this->num) _error2_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
+	if (numindices>this->num) _error_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
 
 	/*go pickup the correct objects, ids and offsets :*/
 	output->num=numindices;
-	if(output->num<1) _error2_("Trying to spawn an empty ElementProperties!");
+	if(output->num<1) _error_("Trying to spawn an empty ElementProperties!");
 
 	output->objects=xNew<Object*>(output->num);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp	(revision 13101)
@@ -110,5 +110,5 @@
 		/*Get first Enum*/
 		if(fread(&record_enum,sizeof(int),1,this->fid)==0){
-			_error2_("Marshalled file is empty");
+			_error_("Marshalled file is empty");
 		}
 		else{
@@ -128,5 +128,5 @@
 				_printLine_("=========================================================================");
 				_printLine_("");
-				_error2_("Enums not consistent (See error message above)");
+				_error_("Enums not consistent (See error message above)");
 			}
 		}
@@ -177,5 +177,5 @@
 	/*Find constant*/
 	Param* param=(Param*)this->constants->FindParamObject(constant_enum);
-	if(!param) _error2_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
+	if(!param) _error_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
 
 	return (Param*)param->copy();
@@ -266,5 +266,5 @@
 					case 1: 
 						/*Read the boolean and broadcast it to other cpus:*/
-						if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error2_("could not read boolean ");
+						if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error_("could not read boolean ");
 						#ifdef _HAVE_MPI_
 						MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
@@ -277,5 +277,5 @@
 					case 2:
 						/*Read the integer and broadcast it to other cpus:*/
-						if(fread(&integer,sizeof(int),1,this->fid)!=1) _error2_("could not read integer ");
+						if(fread(&integer,sizeof(int),1,this->fid)!=1) _error_("could not read integer ");
 						#ifdef _HAVE_MPI_
 						MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
@@ -288,5 +288,5 @@
 					case 3:
 						/*Read the scalar and broadcast it to other cpus:*/
-						if(fread(&scalar,sizeof(IssmPDouble),1,this->fid)!=1) _error2_("could not read scalar ");
+						if(fread(&scalar,sizeof(IssmPDouble),1,this->fid)!=1) _error_("could not read scalar ");
 						#ifdef _HAVE_MPI_
 						MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
@@ -299,5 +299,5 @@
 					case 4: 
 						/*We have to read a string from disk. First read the dimensions of the string, then the string: */
-						if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error2_("could not read length of string ");
+						if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error_("could not read length of string ");
 						#ifdef _HAVE_MPI_
 						MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
@@ -309,5 +309,5 @@
 
 							/*Read string, then broadcast: */
-							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error2_(" could not read string ");
+							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error_(" could not read string ");
 							#ifdef _HAVE_MPI_
 							MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
@@ -360,5 +360,5 @@
 
 					default: 
-						_error2_("unknown record type:" << record_code); 
+						_error_("unknown record type:" << record_code); 
 						break;;
 				}
@@ -428,5 +428,5 @@
 
 				default: 
-					_error2_("unknown record type:" << record_code); 
+					_error_("unknown record type:" << record_code); 
 					break;;
 				}
@@ -453,9 +453,9 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 
-	if(code!=1)_error2_("expecting a boolean for enum " << EnumToStringx(data_enum));
+	if(code!=1)_error_("expecting a boolean for enum " << EnumToStringx(data_enum));
 	
 	/*We have to read a boolean from disk. */
 	if(my_rank==0){  
-		if(fread(&booleanint,sizeof(int),1,fid)!=1) _error2_("could not read boolean ");
+		if(fread(&booleanint,sizeof(int),1,fid)!=1) _error_("could not read boolean ");
 	}
 	#ifdef _HAVE_MPI_
@@ -482,9 +482,9 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 	
-	if(code!=2)_error2_("expecting an integer for enum " << EnumToStringx(data_enum));
+	if(code!=2)_error_("expecting an integer for enum " << EnumToStringx(data_enum));
 	
 	/*We have to read a integer from disk. First read the dimensions of the integer, then the integer: */
 	if(my_rank==0){  
-		if(fread(&integer,sizeof(int),1,fid)!=1) _error2_("could not read integer ");
+		if(fread(&integer,sizeof(int),1,fid)!=1) _error_("could not read integer ");
 	}
 
@@ -512,9 +512,9 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 	
-	if(code!=3)_error2_("expecting a IssmDouble for enum " << EnumToStringx(data_enum));
+	if(code!=3)_error_("expecting a IssmDouble for enum " << EnumToStringx(data_enum));
 	
 	/*We have to read a scalar from disk. First read the dimensions of the scalar, then the scalar: */
 	if(my_rank==0){
-		if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1)_error2_("could not read scalar ");
+		if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
 	}
 	#ifdef _HAVE_MPI_
@@ -542,5 +542,5 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 	
-	if(code!=4)_error2_("expecting a string for enum " << EnumToStringx(data_enum));
+	if(code!=4)_error_("expecting a string for enum " << EnumToStringx(data_enum));
 	
 	/*Now fetch: */
@@ -548,5 +548,5 @@
 	/*We have to read a string from disk. First read the dimensions of the string, then the string: */
 	if(my_rank==0){  
-		if(fread(&string_size,sizeof(int),1,fid)!=1) _error2_("could not read length of string ");
+		if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
 	}
 
@@ -562,5 +562,5 @@
 		/*Read string on node 0, then broadcast: */
 		if(my_rank==0){  
-			if(fread(string,string_size*sizeof(char),1,fid)!=1)_error2_(" could not read string ");
+			if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
 		}
 		#ifdef _HAVE_MPI_
@@ -596,5 +596,5 @@
 	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
 
-	if((code!=5) && (code!=6) && (code!=7))_error2_("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));
 	
 	/*Now fetch: */
@@ -603,5 +603,5 @@
 	/*numberofelements: */
 	if(my_rank==0){  
-		if(fread(&M,sizeof(int),1,fid)!=1) _error2_("could not read number of rows for matrix ");
+		if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
 	}
 
@@ -611,5 +611,5 @@
 
 	if(my_rank==0){  
-		if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns for matrix ");
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
 	}
 	#ifdef _HAVE_MPI_
@@ -623,5 +623,5 @@
 		/*Read matrix on node 0, then broadcast: */
 		if(my_rank==0){  
-			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
 		}
 		
@@ -667,5 +667,5 @@
 	/*Set file pointer to beginning of the data: */
 	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
-	if((code!=5) && (code!=6) && (code!=7))_error2_("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));
 	
 	/*Now fetch: */
@@ -674,5 +674,5 @@
 	/*numberofelements: */
 	if(my_rank==0){  
-		if(fread(&M,sizeof(int),1,fid)!=1) _error2_("could not read number of rows for matrix ");
+		if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
 	}
 	#ifdef _HAVE_MPI_
@@ -681,5 +681,5 @@
 
 	if(my_rank==0){  
-		if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns for matrix ");
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
 	}
 	#ifdef _HAVE_MPI_
@@ -693,5 +693,5 @@
 		/*Read matrix on node 0, then broadcast: */
 		if(my_rank==0){  
-			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
 		}
 		#ifdef _HAVE_MPI_
@@ -729,9 +729,9 @@
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 	
-	if(code!=9)_error2_("expecting a string array for enum " << EnumToStringx(data_enum));
+	if(code!=9)_error_("expecting a string array for enum " << EnumToStringx(data_enum));
 	
 	/*We have to read a bunch of strings from disk. First read the number of strings, and allocate: */
 	if(my_rank==0){  
-		if(fread(&numstrings,sizeof(int),1,fid)!=1) _error2_("could not read length of string array");
+		if(fread(&numstrings,sizeof(int),1,fid)!=1) _error_("could not read length of string array");
 	}
 	#ifdef _HAVE_MPI_
@@ -748,5 +748,5 @@
 			
 			if(my_rank==0){  
-				if(fread(&string_size,sizeof(int),1,fid)!=1) _error2_("could not read length of string ");
+				if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
 			}
 			#ifdef _HAVE_MPI_
@@ -759,5 +759,5 @@
 				/*Read string on node 0, then broadcast: */
 				if(my_rank==0){  
-					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error2_(" could not read string ");
+					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
 				}
 				#ifdef _HAVE_MPI_
@@ -800,9 +800,9 @@
 	/*Set file pointer to beginning of the data: */
 	fid=this->SetFilePointerToData(&code,NULL,data_enum);
-	if(code!=8)_error2_("expecting a IssmDouble mat array for enum " << EnumToStringx(data_enum));
+	if(code!=8)_error_("expecting a IssmDouble mat array for enum " << EnumToStringx(data_enum));
 	
 	/*Now fetch: */
 	if(my_rank==0){  
-		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error2_("could not read number of records in matrix array ");
+		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error_("could not read number of records in matrix array ");
 	}
 	#ifdef _HAVE_MPI_
@@ -827,5 +827,5 @@
 
 			if(my_rank==0){  
-				if(fread(&M,sizeof(int),1,fid)!=1) _error2_("could not read number of rows in " << i << "th matrix of matrix array");
+				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows in " << i << "th matrix of matrix array");
 			}
 			#ifdef _HAVE_MPI_
@@ -834,5 +834,5 @@
 
 			if(my_rank==0){  
-				if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns in " << i << "th matrix of matrix array");
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns in " << i << "th matrix of matrix array");
 			}
 			#ifdef _HAVE_MPI_
@@ -846,5 +846,5 @@
 				/*Read matrix on node 0, then broadcast: */
 				if(my_rank==0){  
-					if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+					if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
 				}
 
@@ -912,5 +912,5 @@
 			  }
 		default:
-			  _error2_("Option of format " << code << " not supported yet");
+			  _error_("Option of format " << code << " not supported yet");
 	}
 
@@ -941,5 +941,5 @@
 		_assert_(dataenum<MaximumNumberOfEnums);
 		if(this->data[dataenum]){
-			_error2_("Info: trying to fetch " << EnumToStringx(dataenum) << " but previous pointer has not been freed (DeleteData has not been called)");
+			_error_("Info: trying to fetch " << EnumToStringx(dataenum) << " but previous pointer has not been freed (DeleteData has not been called)");
 		}
 		#endif
@@ -1141,5 +1141,5 @@
 			break; /*}}}*/
 		default: /*{{{*/
-			_error2_("data code " << code << " not supported yet!");
+			_error_("data code " << code << " not supported yet!");
 			break;
 			/*}}}*/
@@ -1232,5 +1232,5 @@
 #ifdef _HAVE_MPI_
 	MPI_Bcast(&found,1,MPI_INT,0,MPI_COMM_WORLD); 
-	if(!found)_error2_("could not find data with name" << " " << EnumToStringx(data_enum) << " ");
+	if(!found)_error_("could not find data with name" << " " << EnumToStringx(data_enum) << " ");
 #endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp	(revision 13101)
@@ -60,28 +60,28 @@
 	int i;
 
-	if (this->anisomax<1) _error2_("'anisomax' option should be >=1");
-	if (this->coeff==0) _error2_("'coeff' should be positive");
-	if (this->errg<0) _error2_("'errg' option should be >0");
-	if (this->gradation<1) _error2_("'gradation' option should be >=1");
-	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error2_("'Hessiantype' supported options are 0 and 1");
-	if (this->maxnbv<3) _error2_("'maxnbv' option should be >3");
-	if (this->maxsubdiv<=1) _error2_("'maxsubdiv' should be >1");
-	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error2_("'Metrictype' supported options are 0, 1 and 2");
-	if (this->nbjacobi<=0) _error2_("'nbjacobi' option should be >0");
-	if (this->nbsmooth<=0) _error2_("'nbsmooth' option should be >0");
+	if (this->anisomax<1) _error_("'anisomax' option should be >=1");
+	if (this->coeff==0) _error_("'coeff' should be positive");
+	if (this->errg<0) _error_("'errg' option should be >0");
+	if (this->gradation<1) _error_("'gradation' option should be >=1");
+	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error_("'Hessiantype' supported options are 0 and 1");
+	if (this->maxnbv<3) _error_("'maxnbv' option should be >3");
+	if (this->maxsubdiv<=1) _error_("'maxsubdiv' should be >1");
+	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error_("'Metrictype' supported options are 0, 1 and 2");
+	if (this->nbjacobi<=0) _error_("'nbjacobi' option should be >0");
+	if (this->nbsmooth<=0) _error_("'nbsmooth' option should be >0");
 
-	if (this->Crack!=0  && this->Crack!=1) _error2_("'Crack' supported options are 0 and 1");
-	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error2_("'KeepVertices' supported options are 0 and 1");
-	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error2_("'geometricalmetric' supported options are 0 and 1");
+	if (this->Crack!=0  && this->Crack!=1) _error_("'Crack' supported options are 0 and 1");
+	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error_("'KeepVertices' supported options are 0 and 1");
+	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error_("'geometricalmetric' supported options are 0 and 1");
 
-	if (this->hmin<=0) _error2_("'hmin' option should be >0");
-	if (this->hmax<=0 || this->hmax<this->hmin) _error2_("'hmax' option should be between 0 and hmin=" << this->hmin);
-	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error2_("'hminVertices' should be a column");
-	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error2_("'hmaxVertices' should be a column");
-	if (this->hVertices && this->hVerticesSize[1]!=1) _error2_("'hVertices' should be a column");
-	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error2_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
+	if (this->hmin<=0) _error_("'hmin' option should be >0");
+	if (this->hmax<=0 || this->hmax<this->hmin) _error_("'hmax' option should be between 0 and hmin=" << this->hmin);
+	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error_("'hminVertices' should be a column");
+	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error_("'hmaxVertices' should be a column");
+	if (this->hVertices && this->hVerticesSize[1]!=1) _error_("'hVertices' should be a column");
+	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
 	if (this->field){
-		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error2_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
-		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error2_("'err' option should be >0");};
+		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error_("'err' option should be >0");};
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h	(revision 13101)
@@ -31,10 +31,10 @@
 					};
 					/*Object functions*/
-					void    Echo()       {_error2_("not implemented yet"); };
-					void    DeepEcho()   {_error2_("not implemented yet"); };
-					int     Id()         {_error2_("not implemented yet"); };
-					int     MyRank()     {_error2_("not implemented yet"); };
-					int     ObjectEnum() {_error2_("not implemented yet"); };
-					Object *copy()       {_error2_("not implemented yet"); };
+					void    Echo()       {_error_("not implemented yet"); };
+					void    DeepEcho()   {_error_("not implemented yet"); };
+					int     Id()         {_error_("not implemented yet"); };
+					int     MyRank()     {_error_("not implemented yet"); };
+					int     ObjectEnum() {_error_("not implemented yet"); };
+					Object *copy()       {_error_("not implemented yet"); };
 			};
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp	(revision 13101)
@@ -76,5 +76,5 @@
 		}
 		else{
-			_error2_("Metrictype " << Metrictype << " not supported yet (use 0,1 or 2(default))");
+			_error_("Metrictype " << Metrictype << " not supported yet (use 0,1 or 2(default))");
 		}
 
@@ -146,5 +146,5 @@
 			j = NextEdge[jc];
 			if (k>=2000){
-				_error2_("k>=2000 (Maximum number of iterations reached)");
+				_error_("k>=2000 (Maximum number of iterations reached)");
 			}
 		} while ( tbegin != tria); 
@@ -213,5 +213,5 @@
 				j = NextEdge[jc];
 				if (k>=2000){
-					_error2_("k>=2000");
+					_error_("k>=2000");
 				}
 			}while ( tbegin != tria); 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp	(revision 13101)
@@ -45,5 +45,5 @@
 
 		/*some shecks*/
-		if (!(adj[0]==&e || adj[1]==&e)){ _error2_("Intersection bug"); }
+		if (!(adj[0]==&e || adj[1]==&e)){ _error_("Intersection bug"); }
 		_assert_(adj[0]==&e || adj[1]==&e);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp	(revision 13101)
@@ -76,11 +76,11 @@
 
 		//some checks
-		if (bamggeom->Vertices==NULL) _error2_("the domain provided does not contain any vertex");
-		if (bamggeom->Edges==NULL) _error2_("the domain provided does not contain any edge");
+		if (bamggeom->Vertices==NULL) _error_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error_("the domain provided does not contain any edge");
 
 		//Vertices
 		if (bamggeom->Vertices){
 			if(verbose>5) _printLine_("      processing Vertices");
-			if (bamggeom->VerticesSize[1]!=3) _error2_("Vertices should have 3 columns");
+			if (bamggeom->VerticesSize[1]!=3) _error_("Vertices should have 3 columns");
 			vertices = new GeomVertex[nbv];
 			for (i=0;i<nbv;i++) {
@@ -115,8 +115,8 @@
 			 */
 			coefIcoor=(MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
-			if(coefIcoor<=0) _error2_("coefIcoor should be positive");
+			if(coefIcoor<=0) _error_("coefIcoor should be positive");
 		}
 		else{
-			_error2_("No BamgVertex provided");
+			_error_("No BamgVertex provided");
 		}
 
@@ -127,5 +127,5 @@
 
 			if(verbose>5) _printLine_("      processing Edges");
-			if (bamggeom->EdgesSize[1]!=3) _error2_("Edges should have 3 columns");
+			if (bamggeom->EdgesSize[1]!=3) _error_("Edges should have 3 columns");
 			edges = new GeomEdge[nbe];
 
@@ -176,5 +176,5 @@
 		}
 		else{
-			_error2_("No edges provided");
+			_error_("No edges provided");
 		}
 
@@ -206,5 +206,5 @@
 		if (bamggeom->TangentAtEdges){
 			if(verbose>5) _printString_("      processing TangentAtEdges");
-			if (bamggeom->TangentAtEdgesSize[1]!=4) _error2_("TangentAtEdges should have 4 columns");
+			if (bamggeom->TangentAtEdgesSize[1]!=4) _error_("TangentAtEdges should have 4 columns");
 			int n,i,j,k;
 			R2 tg;
@@ -216,6 +216,6 @@
 				tg.x=bamggeom->TangentAtEdges[k*4+2];
 				tg.y=bamggeom->TangentAtEdges[k*4+3];
-				if (i<0 || i>=nbe) _error2_("TangentAtEdges first index exceeds matrix dimension");
-				if (j!=0 && j!=1)  _error2_("TangentAtEdges second index should be 1 or 2 only");
+				if (i<0 || i>=nbe) _error_("TangentAtEdges first index exceeds matrix dimension");
+				if (j!=0 && j!=1)  _error_("TangentAtEdges second index should be 1 or 2 only");
 				edges[i].tg[j] = tg;
 			}
@@ -225,9 +225,9 @@
 		if(bamggeom->Corners){
 			if(verbose>5) _printString_("      processing Corners");
-			if (bamggeom->CornersSize[1]!=1) _error2_("Corners should have 1 column");
+			if (bamggeom->CornersSize[1]!=1) _error_("Corners should have 1 column");
 			n=bamggeom->CornersSize[0];
 			for (i=0;i<n;i++) {     
 				j=(int)bamggeom->Corners[i]-1; //for C indexing
-				if (j>nbv-1 || j<0) _error2_("Bad corner definition: should in [0 " << nbv << "]");
+				if (j>nbv-1 || j<0) _error_("Bad corner definition: should in [0 " << nbv << "]");
 				/*Required => at the same time SetRequired and SetCorner*/
 				vertices[j].SetCorner();
@@ -239,9 +239,9 @@
 		if(bamggeom->RequiredVertices){
 			if(verbose>5) _printLine_("      processing RequiredVertices");
-			if (bamggeom->RequiredVerticesSize[1]!=1) _error2_("RequiredVertices should have 1 column");
+			if (bamggeom->RequiredVerticesSize[1]!=1) _error_("RequiredVertices should have 1 column");
 			n=bamggeom->RequiredVerticesSize[0];
 			for (i=0;i<n;i++) {     
 				j=(int)bamggeom->RequiredVertices[i]-1; //for C indexing
-				if (j>nbv-1 || j<0) _error2_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
+				if (j>nbv-1 || j<0) _error_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
 				vertices[j].SetRequired();
 			}
@@ -251,9 +251,9 @@
 		if(bamggeom->RequiredEdges){
 			if(verbose>5) _printLine_("      processing RequiredEdges");
-			if (bamggeom->RequiredEdgesSize[1]!=1) _error2_("RequiredEdges should have 1 column");
+			if (bamggeom->RequiredEdgesSize[1]!=1) _error_("RequiredEdges should have 1 column");
 			n=bamggeom->RequiredEdgesSize[0];
 			for (i=0;i<n;i++) {     
 				j=(int)bamggeom->RequiredEdges[i]-1; //for C indexing
-				if (j>nbe-1 || j<0) _error2_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
+				if (j>nbe-1 || j<0) _error_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
 				edges[j].SetRequired();  
 			}
@@ -263,5 +263,5 @@
 		if(bamggeom->SubDomains){
 			if(verbose>5) _printLine_("      processing SubDomains");
-			if (bamggeom->SubDomainsSize[1]!=4) _error2_("SubDomains should have 4 columns");
+			if (bamggeom->SubDomainsSize[1]!=4) _error_("SubDomains should have 4 columns");
 			nbsubdomains=bamggeom->SubDomainsSize[0];
 			subdomains = new GeomSubDomain[nbsubdomains];
@@ -271,6 +271,6 @@
 				i2=(int)bamggeom->SubDomains[i*4+2];
 				i3=(int)bamggeom->SubDomains[i*4+3];
-				if (i0!=2) _error2_("Bad Subdomain definition: first number should be 2 (for Edges)");
-				if (i1>nbe || i1<=0) _error2_("Bad Subdomain definition: second number should in [1 " << nbe << "] (edge number)");
+				if (i0!=2) _error_("Bad Subdomain definition: first number should be 2 (for Edges)");
+				if (i1>nbe || i1<=0) _error_("Bad Subdomain definition: second number should in [1 " << nbe << "] (edge number)");
 				subdomains[i].edge=edges + (i1-1);
 				subdomains[i].direction = (int) i2;
@@ -532,5 +532,5 @@
 				delete [] head_v;
 				delete [] eangle;
-				_error2_("two points of the geometry are very closed to each other (see reference numbers above)");
+				_error_("two points of the geometry are very closed to each other (see reference numbers above)");
 			}
 
@@ -610,5 +610,5 @@
 				delete [] head_v;
 				delete [] eangle;
-				_error2_("Length of edge " << i << " is 0");
+				_error_("Length of edge " << i << " is 0");
 			}
 			//compute angle in [-Pi Pi]
@@ -704,5 +704,5 @@
 				long i1 = n1/2 ,j1=n1%2;
 
-				if( edges[i1].v[j1] != edges[i].v[j]) _error2_("Problem while processing edges: check the edge list");
+				if( edges[i1].v[j1] != edges[i].v[j]) _error_("Problem while processing edges: check the edge list");
 
 				edges[i1].Adj[j1] = edges + i;
@@ -831,8 +831,8 @@
 		GeomEdge* on=e.GeomEdgeHook;
 		if (!on){
-			_error2_("ProjectOnCurve error message: edge provided should be on geometry");
+			_error_("ProjectOnCurve error message: edge provided should be on geometry");
 		}
 		if (!e[0].GeomEdgeHook ||  !e[1].GeomEdgeHook){
-			_error2_("ProjectOnCurve error message: at least one of the vertex of the edge provided is not on geometry");
+			_error_("ProjectOnCurve error message: at least one of the vertex of the edge provided is not on geometry");
 		}
 
@@ -875,5 +875,5 @@
 					_printLine_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before");
 					_printLine_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)");
-					_error2_("see above");
+					_error_("see above");
 				}
 				NbTry++;
@@ -895,5 +895,5 @@
 				_printLine_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before");
 				_printLine_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)");
-				_error2_("see above");
+				_error_("see above");
 			}
 			GeomEdge* tmpge = eg1;
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 13101)
@@ -38,5 +38,5 @@
 		// check Size
 		if (Size<=0){
-			_error2_("Size<=0");
+			_error_("Size<=0");
 		}
 
@@ -268,5 +268,5 @@
 				k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
 				if (k<0){
-					_error2_("k<0");
+					_error_("k<0");
 				}
 				ocut = OppositeEdge[k];
@@ -312,5 +312,5 @@
 				double dij = detj-deti;
 				if (i+j+k != 0 + 1 +2){
-					_error2_("i+j+k != 0 + 1 +2");
+					_error_("i+j+k != 0 + 1 +2");
 				}
 				ba[j] =  detj/dij;
@@ -384,5 +384,5 @@
 					}
 					else {
-						_error2_("Bug Split Edge");
+						_error_("Bug Split Edge");
 					}
 				}
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 13101)
@@ -34,5 +34,5 @@
 					double c01=lEnd-lBegin, c0=(lEnd-s)/c01, c1=(s-lBegin)/c01;
 					if (lBegin>s || s>lEnd){
-						_error2_("lBegin>s || s>lEnd");
+						_error_("lBegin>s || s>lEnd");
 					}
 					return e->F(sBegin*c0+sEnd*c1);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp	(revision 13101)
@@ -117,5 +117,5 @@
 			  delete [] kk;
 			  delete [] refv;
-			  _error2_("imaxnbv != nbv");
+			  _error_("imaxnbv != nbv");
 		  }
 		  for (i=0;i<Tho.nbt;i++)
@@ -128,8 +128,8 @@
 				if (i0<0 || i1<0 || i2<0){
 					delete [] refv;
-					_error2_("i0<0 || i1<0 || i2< 0");
+					_error_("i0<0 || i1<0 || i2< 0");
 				}
 				if (i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
-					_error2_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
+					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
 				}
 				triangles[nbt] = Triangle(this,kk[i0],kk[i1],kk[i2]);
@@ -138,8 +138,8 @@
 			  }
 		  if (kt!=nbt){
-			  _error2_("kt!=nbt");
+			  _error_("kt!=nbt");
 		  }
 		  if (nbt==0 && nbv==0) {
-			  _error2_("All triangles have been removed");
+			  _error_("All triangles have been removed");
 		  }
 		  delete [] kk;
@@ -153,8 +153,8 @@
 
 		  if (!nbsubdomains){
-			  _error2_("nbsubdomains==0");
+			  _error_("nbsubdomains==0");
 		  }
 		  if (!subdomains[0].head || !subdomains[0].head->link){
-			  _error2_("!subdomains[0].head || !subdomains[0].head->link");
+			  _error_("!subdomains[0].head || !subdomains[0].head->link");
 		  }
 
@@ -323,5 +323,5 @@
 			}
 		}
-		if(isorphan) _error2_("Orphan found in mesh, see ids above");
+		if(isorphan) _error_("Orphan found in mesh, see ids above");
 
 		/*Clean up*/
@@ -362,5 +362,5 @@
 		}
 		else{
-			if(verbose>5) _error2_("no Vertices found in the initial mesh");
+			if(verbose>5) _error_("no Vertices found in the initial mesh");
 		}
 
@@ -380,5 +380,5 @@
 		}
 		else{
-			if(verbose>5) _error2_("no Triangles found in the initial mesh");
+			if(verbose>5) _error_("no Triangles found in the initial mesh");
 		}
 
@@ -506,5 +506,5 @@
 				//Check value
 				if(!(i>=0 && j>=0 && i<nbe && j<Gh.nbe)) {
-					_error2_("ReadMesh error: EdgesOnGeomEdge edge provided (line " << i1+1 << ": [" << i+1 << " " << j+1 << "]) is incorrect (must be positive, [0<i<nbe=" << nbe << " 0<j<Gh.nbe=" << Gh.nbe << "]");
+					_error_("ReadMesh error: EdgesOnGeomEdge edge provided (line " << i1+1 << ": [" << i+1 << " " << j+1 << "]) is incorrect (must be positive, [0<i<nbe=" << nbe << " 0<j<Gh.nbe=" << Gh.nbe << "]");
 				}
 				edges[i].GeomEdgeHook=Gh.edges+j;
@@ -522,6 +522,6 @@
 				head=(int)bamgmesh->SubDomains[i*3+1]-1;//C indexing
 				direction=(int)bamgmesh->SubDomains[i*3+2];
-				if (i3!=23) _error2_("Bad Subdomain definition: first number should be 3");
-				if (head<0 || head>=nbt) _error2_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
+				if (i3!=23) _error_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
 				subdomains[i].head = triangles+head;
 			}
@@ -567,7 +567,7 @@
 				for (j=0;j<3;j++){
 					int v=GetId(triangles[i][j]); //jth vertex of the ith triangle
-					if (k>3*nbt-1 || k<0) _error2_("k = " << k << ", nbt = " << nbt);
+					if (k>3*nbt-1 || k<0) _error_("k = " << k << ", nbt = " << nbt);
 					next_1[k]=head_1[v];
-					if (v>nbv-1 || v<0)   _error2_("v = " << v << ", nbv = " << nbv);
+					if (v>nbv-1 || v<0)   _error_("v = " << v << ", nbv = " << nbv);
 					head_1[v]=k++;
 					connectivitysize_1[v]+=1;
@@ -707,5 +707,5 @@
 				}
 				if (!stop){
-					_error2_("Element holding segment [" << i1+1 << " " << i2+1 << "] not found...");
+					_error_("Element holding segment [" << i1+1 << " " << i2+1 << "] not found...");
 				}
 			}
@@ -805,5 +805,5 @@
 				const VertexOnGeom &v=VerticesOnGeomEdge[i];
 				if (!v.OnGeomEdge()){
-					_error2_("A vertices supposed to be OnGeomEdge is actually not");
+					_error_("A vertices supposed to be OnGeomEdge is actually not");
 				}
 				bamgmesh->VerticesOnGeomEdge[i*3+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
@@ -888,7 +888,7 @@
 			for (j=0;j<2;j++){
 				int v=(int)bamgmesh->IssmEdges[i*i2+j]-1; //back to C indexing
-				if (k>2*i1-1 || k<0) _error2_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
+				if (k>2*i1-1 || k<0) _error_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
 				next_2[k]=head_2[v];
-				if (v>nbv-1 || v<0)   _error2_("Index exceed matrix dimensions (v=" << v << " not in [0 " << nbv-1 << "])");
+				if (v>nbv-1 || v<0)   _error_("Index exceed matrix dimensions (v=" << v << " not in [0 " << nbv-1 << "])");
 				head_2[v]=k++;
 				connectivitysize_2[v]+=1;
@@ -1061,5 +1061,5 @@
 		//check that hmax is positive
 		if (hmax<=0){
-			_error2_("hmax<=0");
+			_error_("hmax<=0");
 		}
 
@@ -1090,5 +1090,5 @@
 
 				if (ht<=0 || hn<=0){
-					_error2_("ht<=0 || hn<=0");
+					_error_("ht<=0 || hn<=0");
 				}
 				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
@@ -1115,5 +1115,5 @@
 		}
 		else{
-			_error2_("Hessiantype " << Hessiantype << " not supported yet (1->use Green formula, 0-> double P2 projection)");
+			_error_("Hessiantype " << Hessiantype << " not supported yet (1->use Green formula, 0-> double P2 projection)");
 		}
 	}
@@ -1159,5 +1159,5 @@
 		//some checks
 		if (( infvertexindex <0 ) && (detOld <0) ||  ( infvertexindex >=0  ) && (detOld >0) ){
-			_error2_("inconsistent configuration (Contact ISSM developers)");
+			_error_("inconsistent configuration (Contact ISSM developers)");
 		}
 
@@ -1201,5 +1201,5 @@
 			}
 			else{
-				_error2_("Cannot add a vertex more than once. Check duplicates");
+				_error_("Cannot add a vertex more than once. Check duplicates");
 			}
 		}
@@ -1214,5 +1214,5 @@
 		tt[2]= &triangles[nbt++];
 
-		if (nbt>maxnbt) _error2_("Not enough triangles");
+		if (nbt>maxnbt) _error_("Not enough triangles");
 
 		*tt[1]=*tt[2]=*t;
@@ -1251,5 +1251,5 @@
 
 			if (!rswap) {
-				_error2_("swap the point s is on a edge");
+				_error_("swap the point s is on a edge");
 			}
 		}
@@ -1318,5 +1318,5 @@
 		//check that the mesh is not empty
 		if (nbt<=0 || nbv <=0 ) {
-			_error2_("nbt or nbv is negative (Mesh empty?)");
+			_error_("nbt or nbv is negative (Mesh empty?)");
 		}
 
@@ -1340,5 +1340,5 @@
 		if (nbe !=  edge4->nb()){ 
 			delete [] st;
-			_error2_("Some Double edge in the mesh, the number is " << nbe << ", nbe4=" << edge4->nb()); 
+			_error_("Some Double edge in the mesh, the number is " << nbe << ", nbe4=" << edge4->nb()); 
 		}
 		//keep nbe in nbeold
@@ -1360,5 +1360,5 @@
 					//check that it is not an edge on boundary (should not already exist)
 					if (triangles[i].TriangleAdj(j) || triangles[st[k]/3].TriangleAdj((int) (st[k]%3))){
-						_error2_("problem in Geometry reconstruction: an edge on boundary is duplicated (double element?)");
+						_error_("problem in Geometry reconstruction: an edge on boundary is duplicated (double element?)");
 					}
 					//OK, the element is not on boundary, is belongs to 2 triangles -> build Adjacent triangles list
@@ -1378,5 +1378,5 @@
 					_printLine_("Edge " << (-st[k]+2)%3 << " of triangle " << (-st[k]+2)/3);
 					_printLine_("Edge " << triangles[(-st[k]+2)/3].NuEdgeTriangleAdj((int)((-st[k]+2)%3)) << " of triangle " << GetId(triangles[(-st[k]+2)/3].TriangleAdj((int)((-st[k]+2)%3))));
-					_error2_("An edge belongs to more than 2 triangles");
+					_error_("An edge belongs to more than 2 triangles");
 				}	
 			}
@@ -1460,5 +1460,5 @@
 			//check that we have been through all edges
 			if (k!=nbe){
-				_error2_("problem in edge construction process: k!=nbe (should not happen)");
+				_error_("problem in edge construction process: k!=nbe (should not happen)");
 			}
 			//delete edgessave
@@ -1505,5 +1505,5 @@
 					//check that we have the correct vertex
 					if (v!=edges[i0 ].v[j0]){
-						_error2_("v!=edges[i0 ].v[j0]: this should not happen as the vertex belongs to this edge");
+						_error_("v!=edges[i0 ].v[j0]: this should not happen as the vertex belongs to this edge");
 					}
 
@@ -1522,5 +1522,5 @@
 		//check that nbsubdomains is empty
 		if (nbsubdomains){
-			_error2_("nbsubdomains should be 0");
+			_error_("nbsubdomains should be 0");
 		}
 		nbsubdomains=0;
@@ -1591,5 +1591,5 @@
 		if (k!= nbsubdomains){
 			delete [] colorT;
-			_error2_("k!= nbsubdomains");
+			_error_("k!= nbsubdomains");
 		}
 		//delete colorT and st
@@ -1652,5 +1652,5 @@
 		if (Gh.coefIcoor<=0){
 			delete [] colorV;
-			_error2_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
+			_error_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
 		}
 
@@ -1705,5 +1705,5 @@
 				delete [] len;
 				delete [] colorV;
-				_error2_("problem in Edge4 construction: k != i");
+				_error_("problem in Edge4 construction: k != i");
 			}
 		}
@@ -1734,5 +1734,5 @@
 			}
 			else
-			 _error2_("%i should be >=0");
+			 _error_("%i should be >=0");
 		  }
 
@@ -1768,5 +1768,5 @@
 
 		/*Check size*/
-		if (bamgopts->fieldSize[0] != nbv) _error2_("'field' should have " << nbv << " rows");
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
 
 		//initialization of some variables
@@ -1973,5 +1973,5 @@
 
 		/*Check size*/
-		if (bamgopts->fieldSize[0] != nbv) _error2_("'field' should have " << nbv << " rows");
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
 
 		//initialization of some variables
@@ -2298,5 +2298,5 @@
 				if (splitvertex[i1]==3 || splitvertex[i2]==3){
 					delete [] splitvertex;
-					_error2_("Crossing rifts not supported yet");
+					_error_("Crossing rifts not supported yet");
 				}
 			}
@@ -2376,5 +2376,5 @@
 				//_printLine_(element_renu[GetId(ta.t)] << " -> " << GetId((*ta.t)[0])+1 << " " << GetId((*ta.t)[1])+1 << " " << GetId((*ta.t)[2])+1 << ", edge [" << i1 << "->" << j1 << " " << i2 << "->" << j2 << "]");
 				ta = Next(ta).Adj(); 
-				if (count++>50) _error2_("Maximum number of iteration exceeded");
+				if (count++>50) _error_("Maximum number of iteration exceeded");
 			}while ((tbegin != ta)); 
 		}
@@ -2383,5 +2383,5 @@
 		for(i=0;i<NbCrackedEdges;i++){
 			if (Edgeflags[i]!=2){
-				_error2_("A problem occured: at least one crack edge (number " << i+1 << ") does not belong to 2 elements");
+				_error_("A problem occured: at least one crack edge (number " << i+1 << ") does not belong to 2 elements");
 			}
 		}
@@ -2433,5 +2433,5 @@
 			}
 			if (k!=0) {
-				_error2_("there is " << k << " triangles of mes = 0");
+				_error_("there is " << k << " triangles of mes = 0");
 			}
 
@@ -2447,10 +2447,10 @@
 				if (nbswp) nbfe++;
 				if ( nbswp < 0 && k < 5){
-					_error2_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+					_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
 				}
 			}
 
 			if (k!=0) {
-				_error2_("There are " << k << " lost edges, the boundary might be crossing");
+				_error_("There are " << k << " lost edges, the boundary might be crossing");
 			}
 			for (int j=0;j<nbv;j++){
@@ -2534,5 +2534,5 @@
 			if (nbt == nbtout ||  !NbSubDomTot) {
 				delete [] HeapArete;
-				_error2_("The boundary is not close: all triangles are outside");
+				_error_("The boundary is not close: all triangles are outside");
 			}
 
@@ -2572,5 +2572,5 @@
 						if (k!=nbsubdomains){
 							delete [] mark;
-							_error2_("k!=nbsubdomains");
+							_error_("k!=nbsubdomains");
 						}
 						if(OutSide) 
@@ -2662,5 +2662,5 @@
 							 subdomains[i].head=t=ta;
 							if(t<triangles || t >= triangles+nbt || t->det < 0 || t->link == 0) {
-								_error2_("bad definition of SubSomain " << i);
+								_error_("bad definition of SubSomain " << i);
 							}
 							long it = GetId(t);
@@ -2677,5 +2677,5 @@
 								kkk++;
 								if (mark[GetId(tt)]>=0){
-									_error2_("mark[GetId(tt)]>=0");
+									_error_("mark[GetId(tt)]>=0");
 								}
 								mark[GetId(tt)]=i;
@@ -2686,5 +2686,5 @@
 						ta = Previous(Adj(ta));         
 						if(t == (Triangle *) ta) {
-							_error2_("bad definition of SubSomain " << i);
+							_error_("bad definition of SubSomain " << i);
 						}
 					}
@@ -2848,5 +2848,5 @@
 			//if i is higher than nbv, it means that all the determinants are 0,
 			//all vertices are aligned!
-			if  (++i>=nbv) _error2_("all the vertices are aligned");
+			if  (++i>=nbv) _error_("all the vertices are aligned");
 		}
 		// exchange i et 2 in "orderedvertices" so that
@@ -2984,5 +2984,5 @@
 				long  j=vj.ReferenceNumber; 
 				if (&vj!=orderedvertices[j]){
-					_error2_("&vj!= orderedvertices[j]");
+					_error_("&vj!= orderedvertices[j]");
 				}
 				if(i!=j){ 
@@ -2994,5 +2994,5 @@
 				if (tcvj && !tcvj->link){
 					tcvj->Echo();
-					_error2_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
+					_error_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
 				}
 				quadtree->Add(vj);
@@ -3026,5 +3026,5 @@
 
 		if (!Gh.nbe){
-			_error2_("!Gh.nbe");
+			_error_("!Gh.nbe");
 		}
 		Edge **e= new (Edge* [Gh.nbe]);
@@ -3059,5 +3059,5 @@
 			}
 		}
-		if(kk) _error2_("See above");
+		if(kk) _error_("See above");
 
 		return e;
@@ -3258,5 +3258,5 @@
 				//check i
 				if (i<0 || i>=nbt ){
-					_error2_("Index problem in NewPoints (i=" << i << " not in [0 " << nbt-1 << "])");
+					_error_("Index problem in NewPoints (i=" << i << " not in [0 " << nbt-1 << "])");
 				}
 				//change first_np_or_next_t[i]
@@ -3309,5 +3309,5 @@
 					}
 					if (ta.EdgeVertex(0)!=s){
-						_error2_("ta.EdgeVertex(0)!=s");
+						_error_("ta.EdgeVertex(0)!=s");
 					}
 					ta = Next(Adj(ta));
@@ -3344,5 +3344,5 @@
 		}
 		else {
-			_error2_("ProjectOnCurve On BamgVertex " << BTh.GetId(vA) << " forget call to SetVertexFieldOnBTh");
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vA) << " forget call to SetVertexFieldOnBTh");
 		} 
 
@@ -3355,9 +3355,9 @@
 		}
 		else {
-			_error2_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
 		} 
 		Edge * e = &BhAB;
 		if (!pA || !pB || !e){
-			_error2_("!pA || !pB || !e");
+			_error_("!pA || !pB || !e");
 		}
 		// be carefull the back ground edge e is on same geom edge 
@@ -3365,5 +3365,5 @@
 		//check Is a background Mesh;   
 		if (e<BTh.edges || e>=BTh.edges+BTh.nbe){
-			_error2_("e<BTh.edges || e>=BTh.edges+BTh.nbe");
+			_error_("e<BTh.edges || e>=BTh.edges+BTh.nbe");
 		}
 		// walk on BTh edge 
@@ -3388,5 +3388,5 @@
 		  } 
 		else{ // do the search by walking 
-			_error2_("case not supported yet");
+			_error_("case not supported yet");
 		  }
 
@@ -3452,5 +3452,5 @@
 
 		  }
-		_error2_("Big bug...");
+		_error_("Big bug...");
 		return 0; // just for the compiler 
 	}                  
@@ -3493,5 +3493,5 @@
 	}
 	if (kk != nbe){ 
-		_error2_("There are " << kk-nbe << " double edges in the mesh");
+		_error_("There are " << kk-nbe << " double edges in the mesh");
 	}
 
@@ -3525,5 +3525,5 @@
 			//An edge belongs to 2 triangles
 			else {
-				_error2_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
+				_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
 			}
 		}
@@ -3563,5 +3563,5 @@
 	}
 	if(k) {
-		_error2_(k << " boundary edges (from the geometry) are not defined as mesh edges");
+		_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
 	}
 
@@ -3590,5 +3590,5 @@
 	for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
 	 if  (++i>=nbvb) {
-		 _error2_("ReconstructExistingMesh: All the vertices are aligned");
+		 _error_("ReconstructExistingMesh: All the vertices are aligned");
 	 }
 	//Move this vertex (i) to the 2d position in orderedvertices
@@ -3650,5 +3650,5 @@
 	}
 	if(nbloss) {
-		_error2_("we lost " << nbloss << " existing edges other " << knbe);
+		_error_("we lost " << nbloss << " existing edges other " << knbe);
 	}
 
@@ -3725,5 +3725,5 @@
 	subdomains = savesubdomains;
 	if (k) {
-		_error2_("number of triangles edges alone = " << k);
+		_error_("number of triangles edges alone = " << k);
 	}
 	FindSubDomain();
@@ -3755,5 +3755,5 @@
 
 						_printLine_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required");
-						_error2_("See above (might be cryptic...)");
+						_error_("See above (might be cryptic...)");
 					}
 				}
@@ -3778,13 +3778,13 @@
 			t=t0=subdomains[i].head;
 			if (!t0){ // not empty sub domain
-				_error2_("!t0");
+				_error_("!t0");
 			}
 			do { 
 				long kt = GetId(t);
 				if (kt<0 || kt >= nbt ){
-					_error2_("kt<0 || kt >= nbt");
+					_error_("kt<0 || kt >= nbt");
 				}
 				if (renu[kt]!=-1){
-					_error2_("renu[kt]!=-1");
+					_error_("renu[kt]!=-1");
 				}
 				renu[kt]=k++;
@@ -3803,5 +3803,5 @@
 		}
 		if (k != nbt){
-			_error2_("k != nbt");
+			_error_("k != nbt");
 		}
 		// do the change on all the pointeur 
@@ -3929,5 +3929,5 @@
 	coefIcoor= (MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
 	if (coefIcoor<=0){
-		_error2_("coefIcoor should be positive, a problem in the geometry is likely");
+		_error_("coefIcoor should be positive, a problem in the geometry is likely");
 	}
 
@@ -3965,5 +3965,5 @@
 	}
 
-	if (number_of_errors) _error2_("Fatal error: some triangles have negative areas, see above");
+	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
 }
 /*}}}*/
@@ -4146,5 +4146,5 @@
 			register Triangle* t= vertices[i].t;
 			if (!t){
-				_error2_("!t");
+				_error_("!t");
 			}
 			BamgVertex & vi = vertices[i];
@@ -4154,5 +4154,5 @@
 				ta=Previous(Adj(ta));
 				if (vertices+i != ta.EdgeVertex(1)){
-					_error2_("vertices+i != ta.EdgeVertex(1)");
+					_error_("vertices+i != ta.EdgeVertex(1)");
 				}
 				BamgVertex & vj = *(ta.EdgeVertex(0));
@@ -4160,5 +4160,5 @@
 					j= &vj-vertices;
 					if (j<0 || j >= nbv){
-						_error2_("j<0 || j >= nbv");
+						_error_("j<0 || j >= nbv");
 					}
 					R2 Aij = (R2) vj - (R2) vi;
@@ -4284,5 +4284,5 @@
 					// the first PB is to now a background edge between the 2 vertices
 					if (!edgesGtoB){
-						_error2_("!edgesGtoB");
+						_error_("!edgesGtoB");
 					}
 					ong= ProjectOnCurve(*edgesGtoB[Gh.GetId(edges[i].GeomEdgeHook)],
@@ -4356,5 +4356,5 @@
 			Triangle & t = triangles[i];
 			if (!t.link){
-				_error2_("!t.link");
+				_error_("!t.link");
 			}
 			for(int j=0;j<3;j++)
@@ -4383,5 +4383,5 @@
 										||   (cc=Area2( t[0].r , t[1].r , A.r    )) < 0.0)){
 							_printLine_(ke + nbvold << " not in triangle " << i << " In= " << !!t.link << " " << aa << " " << bb << " " << cc << " " << dd);
-							_error2_("Number of triangles with P2 interpolation Problem");
+							_error_("Number of triangles with P2 interpolation Problem");
 						}
 					}
@@ -4391,5 +4391,5 @@
 										||   (cc=Area2( tt[0].r , tt[1].r , A.r     )) < 0)){
 							_printLine_(ke + nbvold << " not in triangle " << ii << " In= " << !!tt.link << " " << aa << " " << bb << " " << cc << " " << dd);
-							_error2_("Number of triangles with P2 interpolation Problem");
+							_error_("Number of triangles with P2 interpolation Problem");
 						}
 					} 
@@ -4439,5 +4439,5 @@
 						  } // tt 
 						else
-						 _error2_("Bug...");
+						 _error_("Bug...");
 					  } // ke<0	       
 					else
@@ -4452,5 +4452,5 @@
 			  } 
 			if (nbinvisible>=2){
-				_error2_("nbinvisible>=2");
+				_error_("nbinvisible>=2");
 			}
 			switch (nbsplitedge) {
@@ -4464,5 +4464,5 @@
 			} 
 			if (ksplit[i]<40){
-				_error2_("ksplit[i]<40");
+				_error_("ksplit[i]<40");
 			}
 		  }
@@ -4481,5 +4481,5 @@
 			int  ke=(int) (ksplit[i]%10);
 			if (kk>=7 || kk<=0){
-				_error2_("kk>=7 || kk<=0");
+				_error_("kk>=7 || kk<=0");
 			}
 
@@ -4498,5 +4498,5 @@
 
 			if (nbmkadj>=10){
-				_error2_("nbmkadj>=10");
+				_error_("nbmkadj>=10");
 			}
 			// --------------------------
@@ -4516,5 +4516,5 @@
 							t1=t0;
 							if (kedge[3*i+i0]<0){
-								_error2_("kedge[3*i+i0]<0");
+								_error_("kedge[3*i+i0]<0");
 							}
 							BamgVertex * v3 = vertices + kedge[3*i+k0];
@@ -4532,8 +4532,8 @@
 							t2=t1=t0;
 							if (kedge[3*i+k1]<0){
-								_error2_("kedge[3*i+k1]<0");
+								_error_("kedge[3*i+k1]<0");
 							}
 							if (kedge[3*i+k2]<0){
-								_error2_("kedge[3*i+k2]<0");
+								_error_("kedge[3*i+k2]<0");
 							}
 
@@ -4559,5 +4559,5 @@
 							t3=t2=t1=t0;
 							if (kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0){
-								_error2_("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];
@@ -4633,5 +4633,5 @@
 				}
 			if (nbmkadj>13){// 13 = 6 + 4 +
-				_error2_("nbmkadj>13");
+				_error_("nbmkadj>13");
 			}
 
@@ -4759,5 +4759,5 @@
 			quadtree->Add(vi);
 			if (!tcvi || tcvi->det<0){// internal
-				_error2_("!tcvi || tcvi->det < 0");
+				_error_("!tcvi || tcvi->det < 0");
 			}
 			AddVertex(vi,tcvi,det3);
@@ -4802,5 +4802,5 @@
 
 		/*Check that the quadtree does exist*/
-		if (!quadtree) _error2_("no starting triangle provided and no quadtree available");
+		if (!quadtree) _error_("no starting triangle provided and no quadtree available");
 
 		/*Call NearestVertex*/
@@ -4808,6 +4808,6 @@
 
 		/*Check output (Vertex a)*/
-		if (!a)    _error2_("problem while trying to find nearest vertex from a given point. No output found");
-		if (!a->t) _error2_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
+		if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
+		if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
 		_assert_(a>=vertices && a<vertices+nbv);
 
@@ -4844,5 +4844,5 @@
 
 		/*Increase counter*/
-		if (++counter>=10000) _error2_("Maximum number of iteration reached (threshold = " << counter << ").");
+		if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
 
 		j= OppositeVertex[jj];
@@ -4908,5 +4908,5 @@
 
 		//check that the subdomain is not empty
-		if (!t0){ _error2_("At least one subdomain is empty");}
+		if (!t0){ _error_("At least one subdomain is empty");}
 
 		//loop
@@ -4991,5 +4991,5 @@
 		//allocate
 		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];  
-		if(NbVerticesOnGeomVertex >= maxnbv) _error2_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		if(NbVerticesOnGeomVertex >= maxnbv) _error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
 		_assert_(nbv==0);
 		//Build VerticesOnGeomVertex
@@ -5080,5 +5080,5 @@
 								NbNewPoints=0;
 								NbEdgeCurve=0;
-								if (nbvend>=maxnbv) _error2_("maximum number of vertices too low! Check the domain outline or increase maxnbv");
+								if (nbvend>=maxnbv) _error_("maximum number of vertices too low! Check the domain outline or increase maxnbv");
 								lcurve =0;
 								s = lstep; //-1 initially, then length of each sub edge
@@ -5322,5 +5322,5 @@
 		printf("\n");
 		if(NbVerticesOnGeomVertex >= maxnbv){
-			_error2_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+			_error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
 		}
 
@@ -5393,5 +5393,5 @@
 		if (bfind!=Gh.nbcurves){
 			delete [] bcurve;
-			_error2_("problem generating number of curves (" << Gh.nbcurves << " found in the geometry but " << bfind << " curve found in the mesh)");
+			_error_("problem generating number of curves (" << Gh.nbcurves << " found in the geometry but " << bfind << " curve found in the mesh)");
 		}
 
@@ -5492,9 +5492,9 @@
 									double se= (sNew-L0)/LAB;
 									if (se<0 || se>=1.000000001){
-										_error2_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
 									}
 									se = abscisseInterpole(v0.m,v1.m,AB,se,1);
 									if (se<0 || se>1){
-										_error2_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
 									}
 									se = k1         ? se : 1. - se;
@@ -5528,5 +5528,5 @@
 							}
 							if (!ee.adj[k1]) {
-								_error2_("adj edge " << BTh.GetId(ee) << ", nbe=" << nbe << ", Gh.vertices=" << Gh.vertices);
+								_error_("adj edge " << BTh.GetId(ee) << ", nbe=" << nbe << ", Gh.vertices=" << Gh.vertices);
 							}
 							pe = ee.adj[k1]; // next edge
@@ -5566,5 +5566,5 @@
 			if(step==0){
 				if(nbv+NbOfNewPoints > maxnbv) {
-					_error2_("too many vertices on geometry: " << nbv+NbOfNewPoints << " >= " << maxnbv);
+					_error_("too many vertices on geometry: " << nbv+NbOfNewPoints << " >= " << maxnbv);
 				}
 				edges = new Edge[NbOfNewEdge];
@@ -5611,5 +5611,5 @@
 		int dir=0;
 		if (k<0){
-			_error2_("k<0");
+			_error_("k<0");
 		}
 		int kkk=0;  
@@ -5619,5 +5619,5 @@
 			kkk++;
 			if (kkk>=1000){
-				_error2_("kkk>=1000");
+				_error_("kkk>=1000");
 			}
 			BamgVertex  &vI =  *edge.EdgeVertex(0);
@@ -5636,5 +5636,5 @@
 							double IJ2 = IJ_IA + IJ_AJ;
 							if (IJ2==0){
-								_error2_("IJ2==0");
+								_error_("IJ2==0");
 							}
 							a= IJ_AJ/IJ2;
@@ -5650,5 +5650,5 @@
 	int NbSwap =0;
 	if (!a.t || !b.t){ // the 2 vertex is in a mesh
-		_error2_("!a.t || !b.t");
+		_error_("!a.t || !b.t");
 	}
 	int k=0;
@@ -5667,5 +5667,5 @@
 		vbegin =v2;
 		if (!v2){
-			_error2_("!v2");
+			_error_("!v2");
 		}
 		det2 = det(*v2,a,b);
@@ -5684,10 +5684,10 @@
 			tc = Previous(tc);
 			if (!v1 || !v2){
-				_error2_("!v1 || !v2");
+				_error_("!v1 || !v2");
 			}
 			Icoor2 detss = 0,l=0,ks;
 			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
 			 if(l++ > 10000000) {
-				 _error2_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+				 _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);
@@ -5708,5 +5708,5 @@
 		k++;
 		if (k>=2000){
-			_error2_("k>=2000");
+			_error_("k>=2000");
 		}
 		if ( vbegin == v2 ) return -1;// error 
@@ -5780,5 +5780,5 @@
 		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
 		if ( a1<0 || a1>=3 ){
-			_error2_("a1<0 || a1>=3");
+			_error_("a1<0 || a1>=3");
 		}
 
@@ -5792,8 +5792,8 @@
 		Icoor2 detT = det1+det2;
 		if ((det1<=0 ) || (det2<=0)){
-			_error2_("(det1<=0 ) || (det2<=0)");
+			_error_("(det1<=0 ) || (det2<=0)");
 		}
 		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
-			_error2_("(detsa>=0) || (detsb<=0)");
+			_error_("(detsa>=0) || (detsb<=0)");
 		}
 		Icoor2 ndet1 = bamg::det(s1,sa,s2);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp	(revision 13101)
@@ -197,5 +197,5 @@
 		// warning for optimisation S is in [0:0.5] not in [0:1]
 		if (i>=512){
-			_error2_("i>=512");
+			_error_("i>=512");
 		}
 		LastMetricInterpole.lab=l;
@@ -345,5 +345,5 @@
 		}
 		if (r>1 || r<0){
-			_error2_("r>1 || r<0");
+			_error_("r>1 || r<0");
 		}
 		return r ;
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp	(revision 13101)
@@ -50,5 +50,5 @@
 		//check that nbax <=NbOfEdges
 		if (nbax <=NbOfEdges ) {
-			_error2_("SetOfEdges4::add overflow: NbOfEdges=" << NbOfEdges << " > nbax=" << nbax);
+			_error_("SetOfEdges4::add overflow: NbOfEdges=" << NbOfEdges << " > nbax=" << nbax);
 		}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp	(revision 13101)
@@ -16,9 +16,9 @@
 		*this = Th.subdomains[i];
 		if ( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
-			_error2_("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);{
-			_error2_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
 		}
 		edge = ThNew.edges+ Th.GetId(edge);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp	(revision 13101)
@@ -19,8 +19,8 @@
 		long nbv = Th->nbv;
 		if (i<0 || j<0 || k<0){
-			_error2_("i<0 || j<0 || k<0");
+			_error_("i<0 || j<0 || k<0");
 		}
 		if (i>=nbv || j>=nbv || k>=nbv){
-			_error2_("i>=nbv || j>=nbv || k>=nbv");
+			_error_("i>=nbv || j>=nbv || k>=nbv");
 		}
 		vertices[0]=v+i;
@@ -173,5 +173,5 @@
 			//check number of iterations
 			if (k>=2000){
-				_error2_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
+				_error_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
 			}
 		} while (this!= t);
@@ -213,5 +213,5 @@
 		do {
 			while (t->swap(j,koption)){
-				if (k>=20000) _error2_("k>=20000");
+				if (k>=20000) _error_("k>=20000");
 				NbSwap++;
 				k++;
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp	(revision 13101)
@@ -119,5 +119,5 @@
 	}
 	else{
-		_error2_("Penta not supported yet");
+		_error_("Penta not supported yet");
 	}
 
@@ -159,5 +159,5 @@
 	}
 	else{
-		_error2_("Tria not supported yet");
+		_error_("Tria not supported yet");
 	}
 
@@ -221,5 +221,5 @@
 	}
 	else{
-		_error2_("Tria not supported yet (user provided indices " << index1 << " " << index2 << " " << index3 << " " << index4 << ")");
+		_error_("Tria not supported yet (user provided indices " << index1 << " " << index2 << " " << index3 << " " << index4 << ")");
 	}
 
@@ -340,5 +340,5 @@
 			break;
 		default:
-			_error2_("vertex index should be in [0 5]");
+			_error_("vertex index should be in [0 5]");
 
 	}
@@ -359,5 +359,5 @@
 	}
 	else{
-		_error2_("Tria not supported yet");
+		_error_("Tria not supported yet");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp	(revision 13101)
@@ -80,5 +80,5 @@
 	}
 	else
-	 _error2_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+	 _error_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
 
 	/*Initialize static fields as undefined*/
@@ -178,5 +178,5 @@
 	}
 	else
-	 _error2_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+	 _error_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
 
 }
@@ -197,9 +197,9 @@
 /*}}}*/
 /*FUNCTION GaussTria::GaussFromCoords{{{*/
-void GaussTria::GaussFromCoords(IssmPDouble x,IssmPDouble y,IssmPDouble* xyz_list){
+void GaussTria::GaussFromCoords(IssmDouble x,IssmDouble y,IssmDouble* xyz_list){
 
 	/*Intermediaries*/
-	IssmPDouble    area = 0;
-	IssmPDouble    x1,y1,x2,y2,x3,y3;
+	IssmDouble    area = 0;
+	IssmDouble    x1,y1,x2,y2,x3,y3;
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -241,5 +241,5 @@
 			break;
 		default:
-			_error2_("vertex index should be in [0 2]");
+			_error_("vertex index should be in [0 2]");
 
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h	(revision 13101)
@@ -22,7 +22,7 @@
 	public:
 		IssmPDouble weight;
-		IssmPDouble coord1;
-		IssmPDouble coord2;
-		IssmPDouble coord3;
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble coord3;
 		
 	public:
@@ -38,5 +38,5 @@
 		int  end(void);
 		void Echo(void);
-		void GaussFromCoords(IssmPDouble x1,IssmPDouble y1,IssmPDouble* xyz_list);
+		void GaussFromCoords(IssmDouble x1,IssmDouble y1,IssmDouble* xyz_list);
 		void GaussPoint(int ig);
 		void GaussVertex(int iv);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13101)
@@ -39,5 +39,5 @@
 
 	/*Checks*/
-	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h	(revision 13101)
@@ -23,9 +23,9 @@
 		/*Object virtual functions definitions*/
 		void  Echo();
-		void  DeepEcho(){_error2_("Not implemented yet");};
-		int   Id(){_error2_("Not implemented yet");}; 
-		int   MyRank(){_error2_("Not implemented yet");};
-		int   ObjectEnum(){_error2_("Not implemented yet");};
-		Object* copy(){_error2_("Not implemented yet");};
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 
 		/*Variogram functions*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13101)
@@ -39,5 +39,5 @@
 
 	/*Checks*/
-	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h	(revision 13101)
@@ -24,9 +24,9 @@
 		/*Object virtual functions definitions*/
 		void  Echo();
-		void  DeepEcho(){_error2_("Not implemented yet");};
-		int   Id(){_error2_("Not implemented yet");}; 
-		int   MyRank(){_error2_("Not implemented yet");};
-		int   ObjectEnum(){_error2_("Not implemented yet");};
-		Object* copy(){_error2_("Not implemented yet");};
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 
 		/*Variogram functions*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h	(revision 13101)
@@ -24,9 +24,9 @@
 		/*Object virtual functions definitions*/
 		void    Echo();
-		void    DeepEcho()  {_error2_("Not implemented yet"); };
-		int     Id()        {_error2_("Not implemented yet"); };
-		int     MyRank()    {_error2_("Not implemented yet"); };
-		int     ObjectEnum(){_error2_("Not implemented yet"); };
-		Object *copy()      {_error2_("Not implemented yet"); };
+		void    DeepEcho()  {_error_("Not implemented yet"); };
+		int     Id()        {_error_("Not implemented yet"); };
+		int     MyRank()    {_error_("Not implemented yet"); };
+		int     ObjectEnum(){_error_("Not implemented yet"); };
+		Object *copy()      {_error_("Not implemented yet"); };
 
 		/*Management*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp	(revision 13101)
@@ -39,6 +39,6 @@
 
 	/*Checks*/
-	if(power<=0 || power>=2) _error2_("power must be betwwen 0 and 2 (0 < power < 2)");
-	if(slope<=0) _error2_("slope must be positive");
+	if(power<=0 || power>=2) _error_("power must be betwwen 0 and 2 (0 < power < 2)");
+	if(slope<=0) _error_("slope must be positive");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h	(revision 13101)
@@ -23,9 +23,9 @@
 		/*Object virtual functions definitions*/
 		void  Echo();
-		void  DeepEcho(){_error2_("Not implemented yet");};
-		int   Id(){_error2_("Not implemented yet");}; 
-		int   MyRank(){_error2_("Not implemented yet");};
-		int   ObjectEnum(){_error2_("Not implemented yet");};
-		Object* copy(){_error2_("Not implemented yet");};
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 
 		/*Variogram functions*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp	(revision 13101)
@@ -83,5 +83,5 @@
 /*FUNCTION Quadtree::Quadtree(){{{*/
 Quadtree::Quadtree(){
-	_error2_("Constructor not supported");
+	_error_("Constructor not supported");
 
 }
@@ -248,5 +248,5 @@
 	}
 	else{
-		_error2_("Box is not full");
+		_error_("Box is not full");
 	}
 }/*}}}*/
@@ -397,5 +397,5 @@
 			break;
 		default:
-			_error2_("Case " << index << " not supported");
+			_error_("Case " << index << " not supported");
 	}
 	newbox->length=master->length/2;
@@ -574,5 +574,5 @@
 			break;
 		default:
-			_error2_("Case " << this->IsWithinRange(x,y,range) << " not supported");
+			_error_("Case " << this->IsWithinRange(x,y,range) << " not supported");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h	(revision 13101)
@@ -27,9 +27,9 @@
 				/*Object functions (Needed because the Quadtree uses a Container*/
 				void    Echo();
-				void    DeepEcho()  {_error2_("not implemented yet"); };
-				int     Id()        {_error2_("not implemented yet"); };
-				int     MyRank()    {_error2_("not implemented yet"); };
-				int     ObjectEnum(){_error2_("not implemented yet"); };
-				Object *copy()      {_error2_("not implemented yet"); };
+				void    DeepEcho()  {_error_("not implemented yet"); };
+				int     Id()        {_error_("not implemented yet"); };
+				int     MyRank()    {_error_("not implemented yet"); };
+				int     ObjectEnum(){_error_("not implemented yet"); };
+				Object *copy()      {_error_("not implemented yet"); };
 
 				/*Methods*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13101)
@@ -39,5 +39,5 @@
 
 	/*Checks*/
-	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h	(revision 13101)
@@ -23,9 +23,9 @@
 		/*Object virtual functions definitions*/
 		void  Echo();
-		void  DeepEcho(){_error2_("Not implemented yet");};
-		int   Id(){_error2_("Not implemented yet");}; 
-		int   MyRank(){_error2_("Not implemented yet");};
-		int   ObjectEnum(){_error2_("Not implemented yet");};
-		Object* copy(){_error2_("Not implemented yet");};
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 
 		/*Variogram functions*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp	(revision 13101)
@@ -47,5 +47,5 @@
 ElementMatrix::ElementMatrix(ElementMatrix* Ke){
 
-	if(!Ke) _error2_("Input Element Matrix is a NULL pointer");
+	if(!Ke) _error_("Input Element Matrix is a NULL pointer");
 	this->Init(Ke);
 	return;
@@ -63,5 +63,5 @@
 	/*If one of the two matrix is NULL, we copy the other one*/
 	if(!Ke1 && !Ke2){
-		_error2_("Two input element matrices are NULL");
+		_error_("Two input element matrices are NULL");
 	}
 	else if(!Ke1){
@@ -75,5 +75,5 @@
 
 	/*General Case: Ke1 and Ke2 are not empty*/
-	if(!Ke1->dofsymmetrical || !Ke2->dofsymmetrical) _error2_("merging 2 non dofsymmetrical matrices not implemented yet");
+	if(!Ke1->dofsymmetrical || !Ke2->dofsymmetrical) _error_("merging 2 non dofsymmetrical matrices not implemented yet");
 
 	/*Initialize itransformation matrix Ke[P[i]] = Ke2[i]*/
@@ -295,5 +295,5 @@
 	}
 	else{
-		_error2_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
 	}
 
@@ -332,5 +332,5 @@
 	}
 	else{
-		_error2_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
 	}
 
@@ -343,6 +343,6 @@
 	for (int i=0;i<this->nrows;i++){
 		for(int j=0;j<this->ncols;j++){
-			if (xIsNan<IssmDouble>(this->values[i*this->ncols+j])) _error2_("NaN found in Element Matrix");
-			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error2_("Element Matrix values exceeds 1.e+50");
+			if (xIsNan<IssmDouble>(this->values[i*this->ncols+j])) _error_("NaN found in Element Matrix");
+			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error_("Element Matrix values exceeds 1.e+50");
 		}
 	}
@@ -365,5 +365,5 @@
 	/*Transpose indices*/
 	if(!dofsymmetrical){
-		_error2_("not supported yet");
+		_error_("not supported yet");
 	}
 
@@ -378,6 +378,6 @@
 	int i,j;
 	_printLine_("Element Matrix echo:");
-	_printLine_("   nrows: " << nrows);
-	_printLine_("   ncols: " << nrows);
+	_printLine_("   nrows: " << this->nrows);
+	_printLine_("   ncols: " << this->ncols);
 	_printLine_("   dofsymmetrical: " << (dofsymmetrical?"true":"false"));
 
@@ -488,5 +488,5 @@
 	int i;
 
-	if(this->nrows!=this->ncols)_error2_("need square matrix in input!");
+	if(this->nrows!=this->ncols)_error_("need square matrix in input!");
 
 	for(i=0;i<this->nrows;i++){
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp	(revision 13101)
@@ -42,5 +42,5 @@
 	/*If one of the two matrix is NULL, we copy the other one*/
 	if(!pe1 && !pe2){
-		_error2_("Two input element matrices are NULL");
+		_error_("Two input element matrices are NULL");
 	}
 	else if(!pe1){
@@ -210,6 +210,6 @@
 #ifdef _ISSM_DEBUG_ 
 	for (int i=0;i<this->nrows;i++){
-		if (xIsNan<IssmDouble>(this->values[i])) _error2_("NaN found in Element Vector");
-		if (fabs( this->values[i])>1.e+50) _error2_("Element Vector values exceeds 1.e+50");
+		if (xIsNan<IssmDouble>(this->values[i])) _error_("NaN found in Element Vector");
+		if (fabs( this->values[i])>1.e+50) _error_("Element Vector values exceeds 1.e+50");
 	}
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp	(revision 13101)
@@ -51,5 +51,5 @@
 		this->pmatrix=new PetscMat(M,N);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -57,5 +57,5 @@
 		this->smatrix=new SeqMat(M,N);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 }
@@ -74,5 +74,5 @@
 		this->pmatrix=new PetscMat(M,N,sparsity);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -80,5 +80,5 @@
 		this->smatrix=new SeqMat(M,N,sparsity);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 }
 /*}}}*/
@@ -96,5 +96,5 @@
 		this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -102,5 +102,5 @@
 		this->smatrix=new SeqMat(serial_mat,M,N,sparsity);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 	
 }
@@ -119,5 +119,5 @@
 		this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -125,5 +125,5 @@
 		this->smatrix=new SeqMat(M,N,connectivity,numberofdofspernode);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 	
 }
@@ -136,5 +136,5 @@
 		delete this->pmatrix;
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -142,5 +142,5 @@
 		delete this->smatrix;
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 }
@@ -150,10 +150,9 @@
 /*FUNCTION Matrix::Echo{{{*/
 void Matrix::Echo(void){
+	_assert_(this);
 
 	if(type==PetscMatType){
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->Echo();
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -161,5 +160,5 @@
 		this->smatrix->Echo();
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 }
@@ -171,6 +170,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->Assemble();
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -179,5 +176,5 @@
 	}
 	else{
-		_error2_("Matrix type: " << type << " not supported yet!");
+		_error_("Matrix type: " << type << " not supported yet!");
 	}
 }
@@ -191,6 +188,4 @@
 		#ifdef _HAVE_PETSC_
 		norm=this->pmatrix->Norm(norm_type);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -198,5 +193,5 @@
 		norm=this->smatrix->Norm(norm_type);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 	return norm;
@@ -209,6 +204,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->GetSize(pM,pN);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -216,5 +209,5 @@
 		this->smatrix->GetSize(pM,pN);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 	
 }
@@ -226,6 +219,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->GetLocalSize(pM,pN);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -233,5 +224,5 @@
 		this->smatrix->GetLocalSize(pM,pN);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 }
@@ -243,6 +234,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->MatMult(X->pvector,AX->pvector);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -250,5 +239,5 @@
 		this->smatrix->MatMult(X->svector,AX->svector);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 }
@@ -264,6 +253,4 @@
 		#ifdef _HAVE_PETSC_
 		output->pmatrix=this->pmatrix->Duplicate();
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -271,5 +258,5 @@
 		output->smatrix=this->smatrix->Duplicate();
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 	
 	return output;
@@ -284,6 +271,4 @@
 		#ifdef _HAVE_PETSC_
 		output=this->pmatrix->ToSerial();
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -291,5 +276,5 @@
 		output=this->smatrix->ToSerial();
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 
 
@@ -303,6 +288,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->SetValues(m,idxm,n,idxn,values,mode);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -310,5 +293,5 @@
 		this->smatrix->SetValues(m,idxm,n,idxn,values,mode);
 	}
-	else _error2_("Matrix type: " << type << " not supported yet!");
+	else _error_("Matrix type: " << type << " not supported yet!");
 }
 /*}}}*/
@@ -319,6 +302,4 @@
 		#ifdef _HAVE_PETSC_
 		this->pmatrix->Convert(newtype);
-		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -327,7 +308,7 @@
 	}
 	else{
-		_error2_("Matrix type: " << type << " not supported yet!");
-	}
-
-}
-/*}}}*/
+		_error_("Matrix type: " << type << " not supported yet!");
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h	(revision 13101)
@@ -32,8 +32,15 @@
 		/*Matrix constructors, destructors {{{*/
 		Matrix();
+		#ifdef _HAVE_PETSC_
 		Matrix(int M,int N,int type=PetscMatType);
 		Matrix(int M,int N,IssmDouble sparsity,int type=PetscMatType);
 		Matrix(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity,int type=PetscMatType);
 		Matrix(int M,int N,int connectivity,int numberofdofspernode,int type=PetscMatType);
+		#else
+		Matrix(int M,int N,int type=SeqMatType);
+		Matrix(int M,int N,IssmDouble sparsity,int type=SeqMatType);
+		Matrix(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity,int type=SeqMatType);
+		Matrix(int M,int N,int connectivity,int numberofdofspernode,int type=SeqMatType);
+		#endif
 		~Matrix();
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp	(revision 13101)
@@ -51,5 +51,5 @@
 		this->pvector=new PetscVec(M,fromlocalsize);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -57,5 +57,5 @@
 		this->svector=new SeqVec(M,fromlocalsize);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -86,5 +86,5 @@
 		this->pvector=new PetscVec(serial_vec,M);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -92,5 +92,5 @@
 		this->svector=new SeqVec(serial_vec,M);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -103,5 +103,5 @@
 		delete this->pvector;
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -109,5 +109,5 @@
 		delete this->svector;
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 }
 /*}}}*/
@@ -121,5 +121,5 @@
 		this->pvector->Echo();
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -127,5 +127,5 @@
 		this->svector->Echo();
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -138,5 +138,5 @@
 		this->pvector->Assemble();
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -144,5 +144,5 @@
 		this->svector->Assemble();
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -156,5 +156,5 @@
 		this->pvector->SetValues(ssize,list,values,mode);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -162,5 +162,5 @@
 		this->svector->SetValues(ssize,list,values,mode);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 		
@@ -175,5 +175,5 @@
 		this->pvector->SetValue(dof,value,mode);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -181,5 +181,5 @@
 		this->svector->SetValue(dof,value,mode);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -193,5 +193,5 @@
 		this->pvector->GetValue(pvalue,dof);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -199,5 +199,5 @@
 		this->svector->GetValue(pvalue,dof);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -210,5 +210,5 @@
 		this->pvector->GetSize(pM);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -216,5 +216,5 @@
 		this->svector->GetSize(pM);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -241,5 +241,5 @@
 		this->pvector->GetLocalSize(pM);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -247,5 +247,5 @@
 		this->svector->GetLocalSize(pM);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -262,5 +262,5 @@
 		output->pvector=this->pvector->Duplicate();
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -269,5 +269,5 @@
 		output->svector=this->svector->Duplicate();
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 	return output;
@@ -283,5 +283,5 @@
 		this->pvector->Set(value);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -289,5 +289,5 @@
 		this->svector->Set(value);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -301,5 +301,5 @@
 		this->pvector->AXPY(X->pvector,a);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -307,5 +307,5 @@
 		this->svector->AXPY(X->svector,a);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -319,5 +319,5 @@
 		this->pvector->AYPX(X->pvector,a);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -325,5 +325,5 @@
 		this->svector->AYPX(X->svector,a);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 
@@ -339,5 +339,5 @@
 		vec_serial=this->pvector->ToMPISerial();
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -345,5 +345,5 @@
 		vec_serial=this->svector->ToMPISerial();
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 	return vec_serial;
@@ -359,5 +359,5 @@
 		this->pvector->Copy(to->pvector);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -365,5 +365,5 @@
 		this->svector->Copy(to->svector);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 
@@ -379,5 +379,5 @@
 		norm=this->pvector->Norm(norm_type);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -385,5 +385,5 @@
 		norm=this->svector->Norm(norm_type);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 	return norm;
@@ -398,5 +398,5 @@
 		this->pvector->Scale(scale_factor);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -404,5 +404,5 @@
 		this->svector->Scale(scale_factor);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 }
@@ -417,5 +417,5 @@
 		dot=this->pvector->Dot(vector->pvector);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -423,5 +423,5 @@
 		dot=this->svector->Dot(vector->svector);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
+	else _error_("Vector type: " << type << " not supported yet!");
 
 	return dot;
@@ -436,5 +436,5 @@
 		this->pvector->PointwiseDivide(x->pvector,y->pvector);
 		#else
-		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 		#endif
 	}
@@ -442,6 +442,6 @@
 		this->svector->PointwiseDivide(x->svector,y->svector);
 	}
-	else _error2_("Vector type: " << type << " not supported yet!");
-
-}
-/*}}}*/
+	else _error_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h	(revision 13101)
@@ -34,9 +34,13 @@
 		/*Vector constructors, destructors {{{*/
 		Vector();
+		#ifdef _HAVE_PETSC_
+		Vector(Vec petsc_vector);
 		Vector(int M,bool fromlocalsize=false,int type=PetscVecType);
 		Vector(IssmDouble* serial_vec,int pM,int type=PetscVecType);
-		#ifdef _HAVE_PETSC_
-		Vector(Vec petsc_vector);
+		#else
+		Vector(int M,bool fromlocalsize=false,int type=SeqVecType);
+		Vector(IssmDouble* serial_vec,int pM,int type=SeqVecType);
 		#endif
+
 		~Vector();
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13101)
@@ -146,5 +146,5 @@
 		}
 
-		if(!found)_error2_("could not find time segment for constraint");
+		if(!found)_error_("could not find time segment for constraint");
 
 		/*Apply or relax constraint: */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13101)
@@ -128,5 +128,5 @@
 void BoolElementResult::GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdofs){
 
-	_error2_("cannot return vector on vertices");
+	_error_("cannot return vector on vertices");
 } /*}}}*/
 /*FUNCTION BoolElementResult::GetElementVectorFromResults{{{*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13101)
@@ -142,5 +142,5 @@
 	IssmDouble data[6];
 
-	if(numdofs!=6)_error2_("Result " << EnumToStringx(this->enum_type) << " is a PentaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	if(numdofs!=6)_error_("Result " << EnumToStringx(this->enum_type) << " is a PentaP1ElementResult and cannot write vector of " << numdofs << " dofs");
 	for(int i=0;i<6;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
 	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
@@ -150,4 +150,4 @@
 void PentaP1ElementResult::GetElementVectorFromResults(Vector* vector,int dof){
 
-	_error2_("Result " << EnumToStringx(enum_type) << " is a PentaP1ElementResult and should not write vector of size numberofelemenrs");
+	_error_("Result " << EnumToStringx(enum_type) << " is a PentaP1ElementResult and should not write vector of size numberofelemenrs");
 } /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13101)
@@ -130,5 +130,5 @@
 	IssmDouble data[3];
 
-	if(numdofs!=3)_error2_("Result " << EnumToStringx(this->enum_type) << " is a TriaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	if(numdofs!=3)_error_("Result " << EnumToStringx(this->enum_type) << " is a TriaP1ElementResult and cannot write vector of " << numdofs << " dofs");
 	for(int i=0;i<3;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
 	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
@@ -137,4 +137,4 @@
 /*FUNCTION TriaP1ElementResult::GetElementVectorFromResults{{{*/
 void TriaP1ElementResult::GetElementVectorFromResults(Vector* vector,int dof){
-	_error2_("Result " << EnumToStringx(enum_type) << " is a TriaP1ElementResult and should not write vector of size numberofelemenrs");
+	_error_("Result " << EnumToStringx(enum_type) << " is a TriaP1ElementResult and should not write vector of size numberofelemenrs");
 } /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp	(revision 13101)
@@ -67,12 +67,12 @@
 	/*Build neighbors list*/
 	if (xIsNan<IssmDouble>(iomodel->Data(MeshUpperelementsEnum)[index])) penta_elements_ids[1]=this->id; //upper penta is the same penta
-	else                                    penta_elements_ids[1]=(int)(iomodel->Data(MeshUpperelementsEnum)[index]);
+	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data(MeshUpperelementsEnum)[index]));
 	if (xIsNan<IssmDouble>(iomodel->Data(MeshLowerelementsEnum)[index])) penta_elements_ids[0]=this->id; //lower penta is the same penta
-	else                                    penta_elements_ids[0]=(int)(iomodel->Data(MeshLowerelementsEnum)[index]);
+	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data(MeshLowerelementsEnum)[index]));
 	this->InitHookNeighbors(penta_elements_ids);
 
 	/*Build horizontalneighborsids list: */
 	_assert_(iomodel->Data(MeshElementconnectivityEnum));
-	for(i=0;i<3;i++) this->horizontalneighborsids[i]=(int)iomodel->Data(MeshElementconnectivityEnum)[3*index+i]-1;
+	for(i=0;i<3;i++) this->horizontalneighborsids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementconnectivityEnum)[3*index+i])-1;
 
 	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
@@ -146,5 +146,5 @@
 /*FUNCTION Penta::AverageOntoPartition {{{*/
 void  Penta::AverageOntoPartition(Vector* partition_contributions,Vector* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
-	_error2_("Not supported yet!");
+	_error_("Not supported yet!");
 }
 /*}}}*/
@@ -252,6 +252,6 @@
 
 	/*Check analysis_types*/
-	if (analysis_type!=DiagnosticHorizAnalysisEnum) _error2_("Not supported yet!");
-	if (approximation!=StokesApproximationEnum) _error2_("Not supported yet!");
+	if (analysis_type!=DiagnosticHorizAnalysisEnum) _error_("Not supported yet!");
+	if (approximation!=StokesApproximationEnum) _error_("Not supported yet!");
 
 	/*retrieve some parameters: */
@@ -318,5 +318,5 @@
 void  Penta::ComputeStrainRate(Vector* eps){
 
-	_error2_("Not implemented yet");
+	_error_("Not implemented yet");
 
 }
@@ -442,5 +442,5 @@
 		#endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			Ke=CreateKMatrixSlope();
+			Ke=CreateBasalMassMatrix();
 			break;
 		case PrognosticAnalysisEnum:
@@ -464,5 +464,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -500,11 +500,11 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixSlope {{{*/
-ElementMatrix* Penta::CreateKMatrixSlope(void){
+/*FUNCTION Penta::CreateBasalMassMatrix{{{*/
+ElementMatrix* Penta::CreateBasalMassMatrix(void){
 
 	if (!IsOnBed()) return NULL;
 
 	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixSlope();
+	ElementMatrix* Ke=tria->CreateMassMatrix();
 	delete tria->matice; delete tria;
 
@@ -569,5 +569,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -638,5 +638,5 @@
 #endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -888,5 +888,5 @@
 		 return i;
 	}
-	_error2_("Node provided not found among element nodes");
+	_error_("Node provided not found among element nodes");
 
 }
@@ -901,5 +901,5 @@
 	/*Recover input*/
 	Input* input=inputs->GetInput(enumtype);
-	if (!input) _error2_("Input " << EnumToStringx(enumtype) << " not found in element");
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
 
 	/*Checks in debugging mode*/
@@ -950,5 +950,5 @@
 
 	Input* input=inputs->GetInput(enumtype);
-	if(!input) _error2_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
 
 	GaussPenta* gauss=new GaussPenta();
@@ -1045,5 +1045,5 @@
 	#endif
 	default:
-		_error2_("analysis: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+		_error_("analysis: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 }
@@ -1085,5 +1085,5 @@
 	/*Check that both inputs have been found*/
 	if (!vx_input || !vy_input){
-		_error2_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
 	}
 
@@ -1110,5 +1110,5 @@
 	/*Check that both inputs have been found*/
 	if (!vx_input || !vy_input || !vz_input){
-		_error2_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
 	}
 
@@ -1145,5 +1145,5 @@
 	/*Get input (either in element or material)*/
 	Input* input=inputs->GetInput(input_enum);
-	if(!input) _error2_("Input " << EnumToStringx(input_enum) << " not found in element");
+	if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
 
 	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
@@ -1157,5 +1157,5 @@
 	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
 	if(elementresult->InstanceEnum()!=enum_in){
-		_error_("Results of offset %i is %s, when %s was expected",offset,EnumToStringx(elementresult->InstanceEnum()),EnumToStringx(enum_in));
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
 	}  
 	if(interp==P1Enum){
@@ -1208,5 +1208,5 @@
 	/*Make a copy of the original input: */
 	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
 
 	/*ArtificialNoise: */
@@ -1228,6 +1228,6 @@
 		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
 		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
-		if(!new_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
-		if(!old_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!new_inputs[i])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
 	}
 
@@ -1253,13 +1253,13 @@
 	
 	if ((code==5) || (code==1)){ //boolean
-		this->inputs->AddInput(new BoolInput(name,(bool)scalar));
+		this->inputs->AddInput(new BoolInput(name,reCast<bool,IssmDouble>(scalar)));
 	}
 	else if ((code==6) || (code==2)){ //integer
-		this->inputs->AddInput(new IntInput(name,(int)scalar));
+		this->inputs->AddInput(new IntInput(name,reCast<int,IssmDouble>(scalar)));
 	}
 	else if ((code==7) || (code==3)){ //IssmDouble
-		this->inputs->AddInput(new DoubleInput(name,(IssmDouble)scalar));
-	}
-	else _error2_("could not recognize nature of vector from code " << code);
+		this->inputs->AddInput(new DoubleInput(name,scalar));
+	}
+	else _error_("could not recognize nature of vector from code " << code);
 
 }
@@ -1291,5 +1291,5 @@
 		for(i=0;i<6;i++){ 
 			_assert_(iomodel->Data(MeshElementsEnum));
-			penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+			penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
 		}
 
@@ -1327,5 +1327,5 @@
 			this->inputs->AddInput(transientinput);
 		}
-		else _error2_("nodal vector is either numberofnodes (" << numberofvertices << "), or numberofnodes+1 long. Field provided is " << M << " long. Enum " << EnumToStringx(vector_enum));
+		else _error_("nodal vector is either numberofnodes (" << numberofvertices << "), or numberofnodes+1 long. Field provided is " << M << " long. Enum " << EnumToStringx(vector_enum));
 	}
 	else if(vector_type==2){ //element vector
@@ -1336,20 +1336,20 @@
 
 			if (code==5){ //boolean
-				this->inputs->AddInput(new BoolInput(vector_enum,(bool)vector[index]));
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool,IssmDouble>(vector[index])));
 			}
 			else if (code==6){ //integer
-				this->inputs->AddInput(new IntInput(vector_enum,(int)vector[index]));
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int,IssmDouble>(vector[index])));
 			}
 			else if (code==7){ //IssmDouble
-				this->inputs->AddInput(new DoubleInput(vector_enum,(IssmDouble)vector[index]));
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
 			}
-			else _error2_("could not recognize nature of vector from code " << code);
+			else _error_("could not recognize nature of vector from code " << code);
 		}
 		else {
-			_error2_("transient elementary inputs not supported yet!");
+			_error_("transient elementary inputs not supported yet!");
 		}
 	}
 	else{
-		_error2_("Cannot add input for vector type " << vector_type << " (not supported)");
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
 	}
 
@@ -1390,6 +1390,6 @@
 		 original_input=(Input*)penta->matice->inputs->GetInput(enum_type);
 		else
-		 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
-		if(!original_input) _error2_("could not find input with enum " << EnumToStringx(enum_type));
+		 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+		if(!original_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
 
 		/*If first time, initialize total_integrated_input*/
@@ -1402,5 +1402,5 @@
 			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
 			else
-			 _error2_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+			 _error_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
 		}
 
@@ -1450,5 +1450,5 @@
 	 this->matice->inputs->AddInput((Input*)depth_averaged_input);
 	else
-	 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
 }
 /*}}}*/
@@ -1491,8 +1491,8 @@
 	}
 	else{
-		_error2_("object of type " << EnumToStringx(object_type) << " not supported yet");
+		_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
 	}
 	for(i=0;i<num_inputs;i++){
-		if(!base_inputs[i]) _error2_("could not find input with enum " << EnumToStringx(enum_type) << " in object " << EnumToStringx(object_type));
+		if(!base_inputs[i]) _error_("could not find input with enum " << EnumToStringx(enum_type) << " in object " << EnumToStringx(object_type));
 		base_inputs[i]->Extrude();
 	}
@@ -1521,5 +1521,5 @@
 			}
 			else{
-				_error2_("object of type " << EnumToStringx(object_type) << " not supported yet");
+				_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
 			}
 		}
@@ -1540,5 +1540,5 @@
 	/*Make a copy of the original input: */
 	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
 
 	/*Scale: */
@@ -1556,5 +1556,5 @@
 	if (enum_type==MaterialsRheologyBbarEnum) input=this->matice->inputs->GetInput(MaterialsRheologyBEnum);
 	else input=this->inputs->GetInput(enum_type);
-	//if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found in penta->inputs"); why error out? if the requested input does not exist, we should still 
+	//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;
@@ -1626,5 +1626,5 @@
 	/*Recover vertices ids needed to initialize inputs*/
 	for(i=0;i<6;i++){ 
-		penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+		penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
 	}
 
@@ -1633,5 +1633,5 @@
 	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
 		for(i=0;i<num_control_type;i++){
-			switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+			switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
 				case BalancethicknessThickeningRateEnum:
 					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
@@ -1669,5 +1669,5 @@
 					/*Matice will take care of it*/ break;
 				default:
-					_error2_("Control " << EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]) << " not implemented yet");
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
 			}
 		}
@@ -1677,30 +1677,33 @@
 	//Need to know the type of approximation for this element
 	if(iomodel->Data(FlowequationElementEquationEnum)){
-		if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealApproximationEnum){
+		if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealPattynApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealPattynApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealPattynApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==HutterApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HutterApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,HutterApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==StokesApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==L1L2ApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,L1L2ApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==StokesApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,StokesApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealStokesApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealStokesApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealStokesApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynStokesApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynStokesApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynStokesApproximationEnum));
 		}
-		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==NoneApproximationEnum){
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==NoneApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,NoneApproximationEnum));
 		}
 		else{
-			_error2_("Approximation type " << EnumToStringx((int)*(iomodel->Data(FlowequationElementEquationEnum)+index)) << " not supported yet");
+			_error_("Approximation type " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(FlowequationElementEquationEnum)[index])) << " not supported yet");
 		}
 	}
@@ -1786,5 +1789,5 @@
 	#endif
 	default: 
-		_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+		_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 }
@@ -1817,5 +1820,5 @@
 	for(i=0;i<numdof2d;i++){
 		newthickness[i]=solution[doflist[i]];
-		if(xIsNan<IssmDouble>(newthickness[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
 		/*Constrain thickness to be at least 1m*/
 		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
@@ -1850,5 +1853,5 @@
 				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
 			}
-			else _error2_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
 		}
 	}
@@ -1887,5 +1890,5 @@
 	for(int i=0;i<numdof;i++){
 		values[i]=solution[doflist[i]];
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
 	}
 
@@ -1917,5 +1920,5 @@
 		values[i]         =solution[doflist[i]];
 		values[i+numdof2d]=values[i];
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
 	}
 
@@ -1948,20 +1951,23 @@
 
 		case VertexEnum:
-
-			/*New PentaVertexInpu*/
-			IssmDouble values[6];
-
-			/*Get values on the 6 vertices*/
-			for (int i=0;i<6;i++){
-				values[i]=vector[this->nodes[i]->GetVertexDof()];
+			{
+
+				/*New PentaVertexInpu*/
+				IssmDouble values[6];
+
+				/*Get values on the 6 vertices*/
+				for (int i=0;i<6;i++){
+					values[i]=vector[this->nodes[i]->GetVertexDof()];
+				}
+
+				/*update input*/
+				this->inputs->AddInput(new PentaP1Input(name,values));
+				return;
+				break;
 			}
 
-			/*update input*/
-			this->inputs->AddInput(new PentaP1Input(name,values));
-			return;
-
 		default:
 
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 }
@@ -1969,10 +1975,10 @@
 /*FUNCTION Penta::InputUpdateFromVector(int* vector, int name, int type);{{{*/
 void  Penta::InputUpdateFromVector(int* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
 /*FUNCTION Penta::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
 void  Penta::InputUpdateFromVector(bool* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
@@ -2060,5 +2066,5 @@
 
 	for(i=0;i<NUMVERTICES;i++){
-		if (flags[nodes[i]->Sid()]){
+		if (reCast<bool,IssmDouble>(flags[nodes[i]->Sid()])){
 			shelf=true;
 			break;
@@ -2161,5 +2167,5 @@
 	for(i=0;i<NUMVERTICES;i++){
 		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
-		if(old_floating_ice[nodes[i]->Sid()]){
+		if(reCast<bool,IssmDouble>(old_floating_ice[nodes[i]->Sid()])){
 			if(b[i]<=ba[i]){ 
 				b[i]=ba[i];
@@ -2181,5 +2187,5 @@
 					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
 				}
-				else if(migration_style==SoftMigrationEnum && sheet_ungrounding[nodes[i]->Sid()]){
+				else if(migration_style==SoftMigrationEnum && reCast<int,IssmDouble>(sheet_ungrounding[nodes[i]->Sid()])){
 					s[i]=(1-density)*h[i];
 					b[i]=-density*h[i];
@@ -2575,5 +2581,5 @@
 void  Penta::SetClone(int* minranks){
 
-	_error2_("not implemented yet");
+	_error_("not implemented yet");
 }
 /*}}}*/
@@ -2801,14 +2807,14 @@
 
 	/*Intermediaries*/
-	IssmInt i,j;
-	int     penta_type;
-	int     penta_node_ids[6];
-	int     penta_vertex_ids[6];
-	IssmDouble  nodeinputs[6];
-	IssmDouble  yts;
-	int     stabilization;
-	bool    dakota_analysis;
-	bool    isstokes;
-	IssmDouble  beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
+	IssmInt    i,j;
+	int        penta_type;
+	int        penta_node_ids[6];
+	int        penta_vertex_ids[6];
+	IssmDouble nodeinputs[6];
+	IssmDouble yts;
+	int        stabilization;
+	bool       dakota_analysis;
+	bool       isstokes;
+	IssmDouble beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
 
 	/*Fetch parameters: */
@@ -2840,5 +2846,5 @@
 
 	/*Recover vertices ids needed to initialize inputs*/
-	for(i=0;i<6;i++) penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+	for(i=0;i<6;i++) penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
 
 	/*Recover nodes ids needed to initialize the node hook.*/
@@ -2846,5 +2852,5 @@
 		//go recover node ids, needed to initialize the node hook.
 		//WARNING: We assume P1 elements here!!!!!
-		penta_node_ids[i]=iomodel->nodecounter+(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+		penta_node_ids[i]=iomodel->nodecounter+reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
 	}
 
@@ -2942,5 +2948,5 @@
 				this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,nodeinputs));
 			}
-			else _error2_("temperature and waterfraction required for the enthalpy solution");
+			else _error_("temperature and waterfraction required for the enthalpy solution");
 			break;
 
@@ -2959,5 +2965,5 @@
 	/*Go through nodes, and whoever is on the potential_sheet_ungrounding, ends up in nodes_on_iceshelf: */
 	for(i=0;i<NUMVERTICES;i++){
-		if (vertices_potentially_ungrounding[nodes[i]->Sid()]){
+		if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
 			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
 		
@@ -3021,5 +3027,5 @@
 /*FUNCTION Penta::SmearFunction {{{*/
 void  Penta::SmearFunction(Vector* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
-	_error2_("not implemented yet");
+	_error_("not implemented yet");
 }
 /*}}}*/
@@ -3225,19 +3231,22 @@
 			break;
 		case VelEnum:
-
-			/*Get input:*/
-			IssmDouble vel;
-			Input* vel_input;
-
-			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
-			vel_input->GetInputAverage(&vel);
-
-			/*process units if requested: */
-			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
-
-			/*Assign output pointers:*/
-			*presponse=vel;
+			{
+
+				/*Get input:*/
+				IssmDouble vel;
+				Input* vel_input;
+
+				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+				vel_input->GetInputAverage(&vel);
+
+				/*process units if requested: */
+				if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+				/*Assign output pointers:*/
+				*presponse=vel;
+			}
+			break;
 		default:  
-			_error2_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
 	}
 
@@ -3362,5 +3371,5 @@
 		kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
 		D_scalar_conduct=gauss->weight*Jdet*kappa;
-		if(dt) D_scalar_conduct=D_scalar_conduct*dt;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
 
 		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
@@ -3382,5 +3391,5 @@
 
 		D_scalar_advec=gauss->weight*Jdet;
-		if(dt) D_scalar_advec=D_scalar_advec*dt;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
 
 		D[0][0]=D_scalar_advec*vx;D[0][1]=0;                D[0][2]=0;
@@ -3394,5 +3403,5 @@
 
 		/*Transient: */
-		if(dt){
+		if(reCast<bool,IssmDouble>(dt)){
 			GetNodalFunctionsP1(&L[0], gauss);
 			D_scalar_trans=gauss->weight*Jdet;
@@ -3415,5 +3424,5 @@
 			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(dt) D_scalar_stab=D_scalar_stab*dt;
+			if(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
 			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
 
@@ -3435,5 +3444,5 @@
 				}
 			}
-			if(dt){
+			if(reCast<bool,IssmDouble>(dt)){
 				for(i=0;i<numdof;i++){
 					for(j=0;j<numdof;j++){
@@ -3491,5 +3500,5 @@
 				
 		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(rho_ice*heatcapacity);
-		if(dt) D_scalar=dt*D_scalar;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
 
 		TripleMultiply(&basis[0],numdof,1,0,
@@ -3591,5 +3600,5 @@
 
 		D_scalar_conduct=gauss->weight*Jdet*kappa;
-		if(dt) D_scalar_conduct=D_scalar_conduct*dt;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
 
 		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
@@ -3612,5 +3621,5 @@
 
 		D_scalar_advec=gauss->weight*Jdet;
-		if(dt) D_scalar_advec=D_scalar_advec*dt;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
 
 		D[0][0]=D_scalar_advec*vx;    D[0][1]=0;                    D[0][2]=0;
@@ -3624,5 +3633,5 @@
 
 		/*Transient: */
-		if(dt){
+		if(reCast<bool,IssmDouble>(dt)){
 			GetNodalFunctionsP1(&L[0], gauss);
 			D_scalar_trans=gauss->weight*Jdet;
@@ -3647,5 +3656,5 @@
 
 			D_scalar_stab=gauss->weight*Jdet;
-			if(dt) D_scalar_stab=D_scalar_stab*dt;
+			if(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
 			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
 
@@ -3667,5 +3676,5 @@
 				}
 			}
-			if(dt){
+			if(reCast<bool,IssmDouble>(dt)){
 				for(i=0;i<numdof;i++){
 					for(j=0;j<numdof;j++){
@@ -3724,5 +3733,5 @@
 				
 		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(heatcapacity*rho_ice);
-		if(dt) D_scalar=dt*D_scalar;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
 
 		TripleMultiply(&basis[0],numdof,1,0,
@@ -3793,5 +3802,5 @@
 	Input* enthalpy_input=NULL; 
 	Input* enthalpypicard_input=NULL; 
-	if(dt){
+	if(reCast<bool,IssmDouble>(dt)){
 		enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
 	}
@@ -3815,10 +3824,10 @@
 
 		scalar_def=phi/rho_ice*Jdet*gauss->weight;
-		if(dt) scalar_def=scalar_def*dt;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
 
 		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
 
 		/* Build transient now */
-		if(dt){
+		if(reCast<bool,IssmDouble>(dt)){
 			enthalpy_input->GetInputValue(&enthalpy, gauss);
 			scalar_transient=enthalpy*Jdet*gauss->weight;
@@ -3838,5 +3847,5 @@
 
 			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
-			if(dt){
+			if(reCast<bool,IssmDouble>(dt)){
 				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
 			}
@@ -3896,5 +3905,5 @@
 
 		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(h_pmp)/(rho_ice*heatcapacity);
-		if(dt) scalar_ocean=dt*scalar_ocean;
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
 
 		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
@@ -3982,5 +3991,5 @@
 
 			scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(rho_ice);
-			if(dt) scalar=dt*scalar;
+			if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
 
 			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
@@ -4054,5 +4063,5 @@
 	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
 	Input* temperature_input=NULL;
-	if (dt) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
+	if (reCast<bool,IssmDouble>(dt)) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
 	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
 
@@ -4071,10 +4080,10 @@
 
 		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
-		if(dt) scalar_def=scalar_def*dt;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
 
 		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
 
 		/* Build transient now */
-		if(dt){
+		if(reCast<bool,IssmDouble>(dt)){
 			temperature_input->GetInputValue(&temperature, gauss);
 			scalar_transient=temperature*Jdet*gauss->weight;
@@ -4092,5 +4101,5 @@
 
 			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
-			if(dt){
+			if(reCast<bool,IssmDouble>(dt)){
 				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
 			}
@@ -4150,5 +4159,5 @@
 
 		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(t_pmp)/(heatcapacity*rho_ice);
-		if(dt) scalar_ocean=dt*scalar_ocean;
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
 
 		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
@@ -4216,5 +4225,5 @@
 
 			scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(heatcapacity*rho_ice);
-			if(dt) scalar=dt*scalar;
+			if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
 
 			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
@@ -4232,9 +4241,9 @@
 	const int    numdof=NDOF1*NUMVERTICES;
 
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble       values[numdof];
-	IssmDouble       temp;
-	GaussPenta   *gauss=NULL;
+	int         i;
+	int        *doflist = NULL;
+	IssmDouble  values[numdof];
+	IssmDouble  temp;
+	GaussPenta *gauss = NULL;
 
 	/*Get dof list: */
@@ -4314,5 +4323,5 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
 		//if(values[i]<0)      _printLine_("temperature < 0°K found in solution vector");
 		//if(values[i]>275)    _printLine_("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)");
@@ -4348,5 +4357,5 @@
 				break;
 			default:
-				_error2_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
 
 		}
@@ -4384,5 +4393,5 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
 	}
 
@@ -4397,6 +4406,6 @@
 		for(i=0;i<numdof;i++){
 			matpar->EnthalpyToThermal(&temperatures[i],&waterfraction[i],values[i],pressure[i]);
-			if(waterfraction[i]<0) _error2_("Negative water fraction found in solution vector");
-			//if(waterfraction[i]>1) _error2_("Water fraction >1 found in solution vector");
+			if(waterfraction[i]<0) _error_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1) _error_("Water fraction >1 found in solution vector");
 		}
 			
@@ -4426,5 +4435,5 @@
 				break;
 			default:
-				_error2_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
 
 		}
@@ -4454,6 +4463,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	GradientIndexing(&doflist1[0],control_index);
@@ -4472,6 +4481,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	((ControlInput*)input)->ScaleGradient(scale);
@@ -4491,6 +4500,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	GradientIndexing(&doflist1[0],control_index);
@@ -4516,5 +4525,5 @@
 			return NULL;
 		default:
-			_error2_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
 	}
 }
@@ -4706,5 +4715,5 @@
 			return CreatePVectorAdjointStokes();
 		default:
-			_error2_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
 	}
 }
@@ -4795,5 +4804,5 @@
 					break;
 				default:
-					_error2_("approximation " << EnumToStringx(approximation) << " not supported yet");
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
 			}
 			break;
@@ -4815,10 +4824,10 @@
 					break;
 				default:
-					_error2_("approximation " << EnumToStringx(approximation) << " not supported yet");
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
 			}
 			break;
 
 		default:
-			_error2_("control type " << EnumToStringx(control_type) << " not supported yet: ");
+			_error_("control type " << EnumToStringx(control_type) << " not supported yet: ");
 	}
 
@@ -4852,5 +4861,5 @@
 			break;
 		default:
-			_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 	}
 	xDelete<int>(responses);
@@ -5106,5 +5115,5 @@
 		}
 
-		if (input->ObjectEnum()!=ControlInputEnum) _error2_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+		if (input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
 
 		((ControlInput*)input)->UpdateValue(scalar);
@@ -5149,8 +5158,8 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(lambdax[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambday[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambdaz[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambdap[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdap[i])) _error_("NaN found in solution vector");
 	}
 
@@ -5188,6 +5197,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(lambdax[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambday[i]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdax[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i]))       _error_("NaN found in solution vector");
 	}
 
@@ -5390,5 +5399,5 @@
 IssmDouble Penta::ThicknessAbsGradient(bool process_units,int weight_index){
 
-	_error2_("Not implemented yet");
+	_error_("Not implemented yet");
 }
 /*}}}*/
@@ -5405,5 +5414,5 @@
 	/*If on water, return 0: */
 	if(IsOnWater())return 0;
-	_error2_("Not implemented yet");
+	_error_("Not implemented yet");
 
 	tria=(Tria*)SpawnTria(0,1,2);
@@ -5456,9 +5465,9 @@
 	/*Get input (either in element or material)*/
 	Input* input=inputs->GetInput(control_enum);
-	if(!input) _error2_("Input " << EnumToStringx(control_enum) << " not found in element");
+	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
 
 	/*Check that it is a ControlInput*/
 	if (input->ObjectEnum()!=ControlInputEnum){
-		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
 
@@ -5495,5 +5504,5 @@
 
 	if (input->ObjectEnum()!=ControlInputEnum){
-		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
 
@@ -5601,5 +5610,5 @@
 
 		default:
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 
@@ -5608,10 +5617,10 @@
 /*FUNCTION Penta::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
 void  Penta::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
 /*FUNCTION Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
 void  Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
@@ -5656,5 +5665,5 @@
 
 		default:
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 
@@ -6200,4 +6209,6 @@
 		case MacAyealApproximationEnum:
 			return CreateKMatrixDiagnosticMacAyeal2d();
+		case L1L2ApproximationEnum:
+			return CreateKMatrixDiagnosticL1L2();
 		case PattynApproximationEnum:
 			return CreateKMatrixDiagnosticPattyn();
@@ -6215,5 +6226,5 @@
 			return CreateKMatrixDiagnosticPattynStokes();
 		default:
-			_error2_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
 	}
 }
@@ -6226,7 +6237,7 @@
 
 	/*Intermediaries*/
-	int       connectivity[2];
-	int       i,i0,i1,j0,j1;
-	IssmDouble    one0,one1;
+	int         connectivity[2];
+	int         i,i0,i1,j0,j1;
+	IssmDouble  one0,one1;
 
 	/*Initialize Element matrix*/
@@ -6327,18 +6338,18 @@
 	/*Intermediaries */
 	int         i,j,ig,approximation;
-	IssmDouble      Jdet;
-	IssmDouble      viscosity, oldviscosity, newviscosity, viscosity_overshoot;
-	IssmDouble      epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble      epsilons[6]; //6 for stokes
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      B[3][numdof2d];
-	IssmDouble      Bprime[3][numdof2d];
-	IssmDouble      D[3][3]={0.0};            // material matrix, simple scalar matrix.
-	IssmDouble      D_scalar;
-	IssmDouble      Ke_gg_gaussian[numdof2d][numdof2d]; //stiffness matrix evaluated at the gaussian point.
-	Tria*       tria=NULL;
-	Penta*      pentabase=NULL;
-	GaussPenta *gauss=NULL;
-	GaussTria  *gauss_tria=NULL;
+	IssmDouble  Jdet;
+	IssmDouble  viscosity , oldviscosity, newviscosity, viscosity_overshoot;
+	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  epsilons[6];                    //6 for stokes
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg_gaussian[numdof2d][numdof2d];
+	Tria       *tria       = NULL;
+	Penta      *pentabase  = NULL;
+	GaussPenta *gauss      = NULL;
+	GaussTria  *gauss_tria = NULL;
 
 	/*Find penta on bed as this is a macayeal elements: */
@@ -6383,5 +6394,5 @@
 			matice->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
 		}
-		else _error2_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
+		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
 
 		D_scalar=2*newviscosity*gauss->weight*Jdet;
@@ -6453,4 +6464,103 @@
 	delete Ke2;
 	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticL1L2Viscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticL1L2Friction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Viscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Viscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet,viscosity;
+	IssmDouble  epsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  Ke_gg_gaussian[numdof2d][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	Tria       *tria       = NULL;
+	Penta      *pentabase  = NULL;
+	GaussPenta *gauss      = NULL;
+	GaussTria  *gauss_tria = NULL;
+
+	/*Find penta on bed as this is a macayeal elements: */
+	pentabase=GetBasalElement();
+	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,L1L2ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES);
+	Input* vx_input=inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* surf_input=inputs->GetInput(SurfaceEnum); _assert_(surf_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		tria->GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		/*Get viscosity for L1L2 model*/
+		GetL1L2Viscosity(&viscosity,&xyz_list[0][0],gauss,vx_input,vy_input,surf_input);
+
+		for(i=0;i<3;i++) D[i][i]=2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->matice;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Friction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Friction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->matice; delete tria;
+
+	/*clean-up and return*/
 	return Ke;
 }
@@ -7193,4 +7303,6 @@
 		case PattynApproximationEnum:
 			return CreatePVectorDiagnosticPattyn();
+		case L1L2ApproximationEnum:
+			return CreatePVectorDiagnosticL1L2();
 		case HutterApproximationEnum:
 			return NULL;
@@ -7206,5 +7318,5 @@
 			return CreatePVectorDiagnosticPattynStokes();
 		default:
-			_error2_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
 	}
 }
@@ -7346,4 +7458,18 @@
 /*FUNCTION Penta::CreatePVectorDiagnosticMacAyeal{{{*/
 ElementVector* Penta::CreatePVectorDiagnosticMacAyeal(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	delete tria->matice; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticL1L2{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticL1L2(void){
 
 	if (!IsOnBed()) return NULL;
@@ -7719,5 +7845,5 @@
 			return NULL;
 		default:
-			_error2_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
 	}
 }
@@ -7892,10 +8018,10 @@
 	const int    numdof=NDOF2*NUMVERTICES;
 
-	int          i;
-	int          approximation;
-	int*         doflist=NULL;
-	IssmDouble       vx,vy;
-	IssmDouble       values[numdof];
-	GaussPenta*  gauss;
+	int         i;
+	int         approximation;
+	int        *doflist        = NULL;
+	IssmDouble  vx,vy;
+	IssmDouble  values[numdof];
+	GaussPenta *gauss;
 
 	/*Get approximation enum and dof list: */
@@ -8043,4 +8169,73 @@
 }
 /*}}}*/
+/*FUNCTION Penta::GetL1L2Viscosity{{{*/
+void Penta::GetL1L2Viscosity(IssmDouble* pviscosity,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input,Input* surface_input){
+	/*Compute the L1L2 viscosity
+	 *
+	 *      1
+	 * mu = - A^-1 (sigma'_e)^(1-n)
+	 *      2
+	 *
+	 * sigma'_e^2 = |sigma'_//|^2 + |sigma'_perp|^2 (see Perego 2012 eq. 17,18)
+	 *
+	 * L1L2 assumptions:
+	 *
+	 * (1) |eps_b|_// = A (|sigma'_//|^2 + |sigma'_perp|^2)^((n-1)/2) |sigma'_//|
+	 * (2) |sigma'_perp|^2 = |rho g (s-z) grad(s)|^2
+	 *
+	 * Assuming that n = 3, we have a polynom of degree 3 to solve (the only unkown is X=|sigma'_//|)
+	 *
+	 * A X^3 + A |rho g (s-z) grad(s)|^2 X - |eps_b|_// = 0     */
+
+	int        i;
+	IssmDouble z,s,viscosity,p,q,delta;
+	IssmDouble tau_perp,tau_par,eps_b,A;
+	IssmDouble epsilonvx[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilonvy[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilon[5];   /*exx eyy exy exz eyz*/
+	IssmDouble z_list[NUMVERTICES];
+	IssmDouble slope[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !surface_input) _error_("Input missing");
+
+	/*Get tau_perp*/
+	for(i=0;i<NUMVERTICES;i++) z_list[i]=xyz_list[3*i+2];
+	surface_input->GetInputValue(&s,gauss);
+	surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+	PentaRef::GetInputValue(&z,&z_list[0],gauss);
+	tau_perp = matpar->GetRhoIce() * matpar->GetG() * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
+
+	/* Get eps_b*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+	eps_b = sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[0]*epsilon[1] + epsilon[2]*epsilon[2]);
+	if(eps_b==0.){
+		*pviscosity = 2.5e+17;
+		return;
+	}
+
+	/*Get A*/
+	_assert_(matice->GetN()==3.0);
+	A=matice->GetA();
+
+	/*Solve for tau_perp (http://fr.wikipedia.org/wiki/Méthode_de_Cardan)*/
+	p     = tau_perp *tau_perp;
+	q     = - eps_b/A;
+	delta = q *q + p*p*p*4./27.;
+	_assert_(delta>0);
+	tau_par = pow(0.5*(-q+sqrt(delta)),1./3.) - pow(0.5*(q+sqrt(delta)),1./3.);
+
+	/*Viscosity*/
+	viscosity = 1./(2.*A*(tau_par*tau_par + tau_perp*tau_perp));
+	_assert_(!isnan(viscosity));
+	_assert_(viscosity > 0.);
+
+	/*Assign output pointer*/
+	*pviscosity = viscosity;
+	return; 
+}
+/*}}}*/
 /*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHoriz {{{*/
 void  Penta::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
@@ -8061,4 +8256,9 @@
 			return;
 		}
+	}
+	if (approximation==L1L2ApproximationEnum){
+		if (!IsOnBed()) return;
+		InputUpdateFromSolutionDiagnosticL1L2(solution);
+		return;
 	}
 	else if (approximation==PattynApproximationEnum){
@@ -8114,6 +8314,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8212,6 +8412,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8300,8 +8500,8 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzstokes[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(pressure[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8310,10 +8510,10 @@
 	if (vzmacayeal_input){
 		if (vzmacayeal_input->ObjectEnum()!=PentaP1InputEnum){
-			_error2_("Cannot compute Vel as VzMacAyeal is of type " << EnumToStringx(vzmacayeal_input->ObjectEnum()));
+			_error_("Cannot compute Vel as VzMacAyeal is of type " << EnumToStringx(vzmacayeal_input->ObjectEnum()));
 		}
 		GetInputListOnVertices(&vzmacayeal[0],VzMacAyealEnum);
 	}
 	else{
-		_error2_("Cannot update solution as VzMacAyeal is not present");
+		_error_("Cannot update solution as VzMacAyeal is not present");
 	}
 
@@ -8342,4 +8542,85 @@
 	xDelete<int>(doflistm);
 	xDelete<int>(doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticL1L2 {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticL1L2(IssmDouble* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int    *doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,L1L2ApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
+	for(i=0;i<3;i++){
+		vx[i]  =values[i*NDOF2+0];
+		vy[i]  =values[i*NDOF2+1];
+		vx[i+3]=vx[i];
+		vy[i+3]=vy[i];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get parameters fro pressure computation*/
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+
+		/*Get node data: */
+		GetVerticesCoordinates(&xyz_list[0][0],penta->nodes,NUMVERTICES);
+
+		/*Now Compute vel*/
+		GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+		for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+		/*Now compute pressure*/
+		GetInputListOnVertices(&surface[0],SurfaceEnum);
+		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+		/*Now, we have to move the previous Vx and Vy inputs  to old 
+		 * status, otherwise, we'll wipe them off: */
+		penta->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+		penta->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+		penta->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+		/*Add vx and vy as inputs to the tria element: */
+		penta->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+		penta->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+		penta->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+		penta->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
 }
 /*}}}*/
@@ -8379,6 +8660,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8468,8 +8749,8 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzstokes[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(pressure[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8478,10 +8759,10 @@
 	if (vzpattyn_input){
 		if (vzpattyn_input->ObjectEnum()!=PentaP1InputEnum){
-			_error2_("Cannot compute Vel as VzPattyn is of type " << EnumToStringx(vzpattyn_input->ObjectEnum()));
+			_error_("Cannot compute Vel as VzPattyn is of type " << EnumToStringx(vzpattyn_input->ObjectEnum()));
 		}
 		GetInputListOnVertices(&vzpattyn[0],VzPattynEnum);
 	}
 	else{
-		_error2_("Cannot update solution as VzPattyn is not present");
+		_error_("Cannot update solution as VzPattyn is not present");
 	}
 
@@ -8544,6 +8825,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8613,5 +8894,5 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vz[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vz[i])) _error_("NaN found in solution vector");
 	}
 
@@ -8624,8 +8905,8 @@
 		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
 		if (vzstokes_input){
-			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error2_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
 			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
 		}
-		else _error2_("Cannot compute Vz as VzStokes in not present in PattynStokes element");
+		else _error_("Cannot compute Vz as VzStokes in not present in PattynStokes element");
 		for(i=0;i<NUMVERTICES;i++){
 			vzpattyn[i]=vz[i];
@@ -8636,8 +8917,8 @@
 		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
 		if (vzstokes_input){
-			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error2_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
 			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
 		}
-		else _error2_("Cannot compute Vz as VzStokes in not present in MacAyealStokes element");
+		else _error_("Cannot compute Vz as VzStokes in not present in MacAyealStokes element");
 		for(i=0;i<NUMVERTICES;i++){
 			vzmacayeal[i]=vz[i];
@@ -8711,8 +8992,8 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vz[i]))       _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(pressure[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vz[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h	(revision 13101)
@@ -162,6 +162,6 @@
 		IssmDouble SurfaceAverageVelMisfit(bool process_units,int weight_index);
 		IssmDouble ThicknessAbsGradient(bool process_units,int weight_index);
-		IssmDouble ThicknessAlongGradient( bool process_units,int weight_index){_error2_("not supported");};
-		IssmDouble ThicknessAcrossGradient(bool process_units,int weight_index){_error2_("not supported");};
+		IssmDouble ThicknessAlongGradient( bool process_units,int weight_index){_error_("not supported");};
+		IssmDouble ThicknessAcrossGradient(bool process_units,int weight_index){_error_("not supported");};
 		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
 		#endif
@@ -169,6 +169,6 @@
 		/*Penta specific routines:{{{*/
 		void	  BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
+		ElementMatrix* CreateBasalMassMatrix(void);
 		ElementMatrix* CreateKMatrixPrognostic(void);
-		ElementMatrix* CreateKMatrixSlope(void);
 		ElementVector* CreatePVectorPrognostic(void);
 		ElementVector* CreatePVectorSlope(void);
@@ -227,4 +227,7 @@
 		ElementMatrix* CreateKMatrixDiagnosticMacAyealPattyn(void);
 		ElementMatrix* CreateKMatrixDiagnosticMacAyealStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2Viscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2Friction(void);
 		ElementMatrix* CreateKMatrixDiagnosticPattyn(void);
 		ElementMatrix* CreateKMatrixDiagnosticPattynViscous(void);
@@ -245,4 +248,5 @@
 		void           InputUpdateFromSolutionDiagnosticMacAyealPattyn( IssmDouble* solutiong);
 		void           InputUpdateFromSolutionDiagnosticMacAyealStokes( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticL1L2( IssmDouble* solutiong);
 		void           InputUpdateFromSolutionDiagnosticPattyn( IssmDouble* solutiong);
 		void           InputUpdateFromSolutionDiagnosticPattynStokes( IssmDouble* solutiong);
@@ -265,4 +269,5 @@
 		ElementVector* CreatePVectorDiagnosticMacAyealPattyn(void);
 		ElementVector* CreatePVectorDiagnosticMacAyealStokes(void);
+		ElementVector* CreatePVectorDiagnosticL1L2(void);
 		ElementVector* CreatePVectorDiagnosticPattyn(void);
 		ElementVector* CreatePVectorDiagnosticPattynStokes(void);
@@ -273,4 +278,5 @@
 		ElementVector* CreatePVectorDiagnosticVertVolume(void);
 		ElementVector* CreatePVectorDiagnosticVertBase(void);
+		void GetL1L2Viscosity(IssmDouble*, IssmDouble*, GaussPenta*, Input*, Input*, Input*);
 		#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp	(revision 13101)
@@ -949,5 +949,5 @@
 	/*Get Determinant*/
 	Matrix3x3Determinant(Jdet,&J[0][0]);
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
@@ -972,5 +972,5 @@
 	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
 	*Jdet=SQRT3/6.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 }
 /*}}}*/
@@ -990,5 +990,5 @@
 
 	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.) + pow(z2-z1,2.));
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
@@ -1226,5 +1226,5 @@
 	/*Area of a trabezoid = altitude * (base1 + base2)/2 */
 	*Jdet= pow(pow(x2-x1,2.) + pow(y2-y1,2.),0.5) * (z4-z1 + z3-z2)/8;
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h	(revision 13101)
@@ -56,7 +56,7 @@
 		void GetLprimeStokesMacAyeal(IssmDouble* LprimeStokesMacAyeal, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussTria* gauss){_error2_("only PentaGauss are supported");};
+		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussTria* gauss){_error_("only PentaGauss are supported");};
 		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){_error2_("only PentaGauss are supported");};
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){_error_("only PentaGauss are supported");};
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp	(revision 13101)
@@ -193,5 +193,5 @@
 		 #endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			Ke=CreateKMatrixSlope();
+			Ke=CreateMassMatrix();
 			break;
 		case PrognosticAnalysisEnum:
@@ -214,5 +214,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -232,8 +232,8 @@
 	/*Intermediaries */
 	int        i,j,ig;
-	IssmDouble     heatcapacity,latentheat;
-	IssmDouble     Jdet,D_scalar;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     L[3];
+	IssmDouble heatcapacity,latentheat;
+	IssmDouble Jdet,D_scalar;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble L[3];
 	GaussTria *gauss=NULL;
 
@@ -277,5 +277,5 @@
 			return CreateKMatrixPrognostic_DG();
 		default:
-			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
 	}
 
@@ -370,5 +370,5 @@
 		if(stabilization==2){
 			/*Streamline upwinding*/
-			vel=sqrt(pow(vx,2.)+pow(vy,2.))+1.e-8;
+			vel=sqrt(vx*vx+vy*vy)+1.e-8;
 			K[0][0]=h/(2*vel)*vx*vx;
 			K[1][0]=h/(2*vel)*vy*vx;
@@ -477,6 +477,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixSlope {{{*/
-ElementMatrix* Tria::CreateKMatrixSlope(void){
+/*FUNCTION Tria::CreateMassMatrix {{{*/
+ElementMatrix* Tria::CreateMassMatrix(void){
 
 	/*constants: */
@@ -484,9 +484,8 @@
 
 	/* Intermediaries */
-	int        i,j,ig;
-	IssmDouble     DL_scalar,Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     L[1][3];
-	GaussTria *gauss = NULL;
+	IssmDouble  D,Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  L[1][3];
+	GaussTria  *gauss = NULL;
 
 	/*Initialize Element matrix*/
@@ -497,15 +496,15 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 		
 		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
-		DL_scalar=gauss->weight*Jdet;
+		D=gauss->weight*Jdet;
 
 		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF1);
 
 		TripleMultiply(&L[0][0],1,3,1,
-					&DL_scalar,1,1,0,
+					&D,1,1,0,
 					&L[0][0],1,3,0,
 					&Ke->values[0],1);
@@ -568,5 +567,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -587,5 +586,5 @@
 			return CreatePVectorPrognostic_DG();
 		default:
-			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
 	}
 }
@@ -763,5 +762,5 @@
 #endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -775,10 +774,10 @@
 /*FUNCTION Tria::ComputeBasalStress {{{*/
 void  Tria::ComputeBasalStress(Vector* eps){
-	_error2_("Not Implemented yet");
+	_error_("Not Implemented yet");
 }
 /*}}}*/
 /*FUNCTION Tria::ComputeStrainRate {{{*/
 void  Tria::ComputeStrainRate(Vector* eps){
-	_error2_("Not Implemented yet");
+	_error_("Not Implemented yet");
 }
 /*}}}*/
@@ -1088,5 +1087,5 @@
 		 return i;
 	}
-	_error2_("Node provided not found among element nodes");
+	_error_("Node provided not found among element nodes");
 }
 /*}}}*/
@@ -1100,5 +1099,5 @@
 	/*Recover input*/
 	Input* input=inputs->GetInput(enumtype);
-	if (!input) _error2_("Input " << EnumToStringx(enumtype) << " not found in element");
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
 
 	/*Checks in debugging mode*/
@@ -1172,5 +1171,5 @@
 
 	Input* input=inputs->GetInput(enumtype);
-	if(!input) _error2_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
 
 	GaussTria* gauss=new GaussTria();
@@ -1214,5 +1213,5 @@
 	#endif
 	default:
-		_error2_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
 	}
 
@@ -1230,5 +1229,5 @@
 	/*Check that both inputs have been found*/
 	if (!vx_input || !vy_input){
-		_error2_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
 	}
 
@@ -1254,5 +1253,5 @@
 	/*Get input (either in element or material)*/
 	Input* input=inputs->GetInput(input_enum);
-	if(!input) _error2_("Input " << EnumToStringx(input_enum) << " not found in element");
+	if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
 
 	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
@@ -1266,5 +1265,5 @@
 	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
 	if(elementresult->InstanceEnum()!=enum_in){
-		_error_("Results of offset %i is %s, when %s was expected",offset,EnumToStringx(elementresult->InstanceEnum()),EnumToStringx(enum_in));
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
 	}
 	if(interp==P1Enum){
@@ -1304,5 +1303,5 @@
 	/*Make a copy of the original input: */
 	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
 
 	/*ArtificialNoise: */
@@ -1324,6 +1323,6 @@
 		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
 		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
-		if(!new_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
-		if(!old_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!new_inputs[i])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
 	}
 
@@ -1353,6 +1352,6 @@
 	 oldinput=(Input*)this->matice->inputs->GetInput(enum_type);
 	else
-	 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
-	if(!oldinput)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+	if(!oldinput)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
 	newinput=(Input*)oldinput->copy();
 
@@ -1366,5 +1365,5 @@
 	 this->matice->inputs->AddInput((Input*)newinput);
 	else
-	 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
 }
 /*}}}*/
@@ -1384,5 +1383,5 @@
 	/*Make a copy of the original input: */
 	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
 
 	/*Scale: */
@@ -1399,5 +1398,5 @@
 	if (enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum) input=this->matice->inputs->GetInput(enum_type);
 	else input=this->inputs->GetInput(enum_type);
-	//if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
+	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
 	if(!input)return;
 
@@ -1444,13 +1443,13 @@
 
 	/*Intermediaries*/
-	int    i,j;
-	int    tria_vertex_ids[3];
+	int        i,j;
+	int        tria_vertex_ids[3];
 	IssmDouble nodeinputs[3];
 	IssmDouble cmmininputs[3];
 	IssmDouble cmmaxinputs[3];
-	bool   control_analysis=false;
-	int    num_control_type;
+	bool       control_analysis   = false;
+	int        num_control_type;
 	IssmDouble yts;
-	int    num_cm_responses;
+	int        num_cm_responses;
    
 	/*Get parameters: */
@@ -1469,5 +1468,5 @@
 	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
 		for(i=0;i<num_control_type;i++){
-			switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+			switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
 				case BalancethicknessThickeningRateEnum:
 					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
@@ -1506,5 +1505,5 @@
 					/*Matice will take care of it*/ break;
 				default:
-					_error2_("Control " << EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]) << " not implemented yet");
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
 			}
 		}
@@ -1578,5 +1577,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 }
@@ -1596,5 +1595,5 @@
 	for(int i=0;i<numdof;i++){
 		values[i]=solution[doflist[i]];
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
 	}
 
@@ -1629,5 +1628,5 @@
 	for(i=0;i<numdof;i++){
 		newthickness[i]=solution[doflist[i]];
-		if(xIsNan<IssmDouble>(newthickness[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
 		/*Constrain thickness to be at least 1m*/
 		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
@@ -1660,5 +1659,5 @@
 				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
 			}
-			else _error2_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
 		}
 	}
@@ -1701,5 +1700,5 @@
 		}
 		default:
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 }
@@ -1707,10 +1706,10 @@
 /*FUNCTION Tria::InputUpdateFromVector(int* vector, int name, int type);{{{*/
 void  Tria::InputUpdateFromVector(int* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
 /*FUNCTION Tria::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
 void  Tria::InputUpdateFromVector(bool* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
@@ -1730,5 +1729,5 @@
 		this->inputs->AddInput(new DoubleInput(name,reCast<int>(scalar)));
 	}
-	else _error2_("could not recognize nature of vector from code " << code);
+	else _error_("could not recognize nature of vector from code " << code);
 
 }
@@ -1796,5 +1795,5 @@
 			this->inputs->AddInput(transientinput);
 		}
-		else _error2_("nodal vector is either numberofnodes or numberofnodes+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+		else _error_("nodal vector is either numberofnodes or numberofnodes+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
 	}
 	else if(vector_type==2){ //element vector
@@ -1813,12 +1812,12 @@
 				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
 			}
-			else _error2_("could not recognize nature of vector from code " << code);
+			else _error_("could not recognize nature of vector from code " << code);
 		}
 		else {
-			_error2_("transient elementary inputs not supported yet!");
+			_error_("transient elementary inputs not supported yet!");
 		}
 	}
 	else{
-		_error2_("Cannot add input for vector type " << vector_type << " (not supported)");
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
 	}
 
@@ -2248,10 +2247,10 @@
 void  Tria::SetClone(int* minranks){
 
-	_error2_("not implemented yet");
+	_error_("not implemented yet");
 }
 /*}}}*/
 /*FUNCTION Tria::SmearFunction {{{*/
 void  Tria::SmearFunction(Vector*  smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
-	_error2_("not implemented yet");
+	_error_("not implemented yet");
 
 }
@@ -2330,5 +2329,4 @@
 IssmDouble Tria::SurfaceArea(void){
 
-	int    i;
 	IssmDouble S;
 	IssmDouble normal[3];
@@ -2341,5 +2339,5 @@
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
 
-	for (i=0;i<3;i++){
+	for(int i=0;i<3;i++){
 		v13[i]=xyz_list[0][i]-xyz_list[2][i];
 		v23[i]=xyz_list[1][i]-xyz_list[2][i];
@@ -2350,5 +2348,5 @@
 	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
 
-	S = 0.5 * sqrt(pow(normal[0],(IssmDouble)2)+pow(normal[1],(IssmDouble)2)+pow(normal[2],(IssmDouble)2));
+	S = 0.5 * sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
 
 	/*Return: */
@@ -2359,10 +2357,9 @@
 void Tria::SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]){
 
-	int i;
 	IssmDouble v13[3],v23[3];
 	IssmDouble normal[3];
 	IssmDouble normal_norm;
 
-	for (i=0;i<3;i++){
+	for(int i=0;i<3;i++){
 		v13[i]=xyz_list[0][i]-xyz_list[2][i];
 		v23[i]=xyz_list[1][i]-xyz_list[2][i];
@@ -2373,9 +2370,9 @@
 	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
 
-	normal_norm=sqrt( pow(normal[0],(IssmDouble)2)+pow(normal[1],(IssmDouble)2)+pow(normal[2],(IssmDouble)2) );
-
-	*(surface_normal)=normal[0]/normal_norm;
-	*(surface_normal+1)=normal[1]/normal_norm;
-	*(surface_normal+2)=normal[2]/normal_norm;
+	normal_norm=sqrt( normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	*(surface_normal+0) = normal[0]/normal_norm;
+	*(surface_normal+1) = normal[1]/normal_norm;
+	*(surface_normal+2) = normal[2]/normal_norm;
 }
 /*}}}*/
@@ -2400,5 +2397,5 @@
 	this->MaxAbsVy(&maxabsvy,false);
 	#else
-		_error2_("ISSM was not compiled with responses compiled in, exiting!");
+		_error_("ISSM was not compiled with responses compiled in, exiting!");
 	#endif
 
@@ -2593,5 +2590,5 @@
 
 	/*First off, check that this segment belongs to this element: */
-	if ((int)*(segment+4)!=this->id)_error2_("error message: segment with id " << (int)*(segment+4) << " does not belong to element with id:" << this->id);
+	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
 
 	/*Recover segment node locations: */
@@ -2610,5 +2607,5 @@
 	normal[1]=sin(atan2(x1-x2,y2-y1));
 
-	length=sqrt(pow(x2-x1,2.0)+pow(y2-y1,2));
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
 
 	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
@@ -2800,5 +2797,5 @@
 			*presponse=this->matice->GetZbar();
 			break;
-		case VelEnum:
+		case VelEnum:{
 
 			/*Get input:*/
@@ -2813,7 +2810,8 @@
 
 			/*Assign output pointers:*/
-			*presponse=vel;
+			*presponse=vel;}
+			break;
 		default:  
-			_error2_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
 	}
 
@@ -2978,5 +2976,5 @@
 		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
 		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
-		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+		slope_magnitude=sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
 		if(slope_magnitude>MAXSLOPE) alpha2=pow((IssmDouble)10,MOUNTAINKEXPONENT);
 		else friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
@@ -3302,11 +3300,11 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
 	/*Get Vz and compute vel*/
 	GetInputListOnVertices(&vz[0],VzEnum,0);
-	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	for(i=0;i<NUMVERTICES;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 
 	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
@@ -3362,11 +3360,11 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
 	}
 
 	/*Now Compute vel*/
 	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
-	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	for(i=0;i<NUMVERTICES;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 
 	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
@@ -3418,5 +3416,5 @@
 
 		if (input->ObjectEnum()!=ControlInputEnum){
-			_error2_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
 		}
 
@@ -3443,6 +3441,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	GradientIndexing(&doflist1[0],control_index);
@@ -3461,6 +3459,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	((ControlInput*)input)->ScaleGradient(scale);
@@ -3480,6 +3478,6 @@
 		input=inputs->GetInput(enum_type);
 	}
-	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
 	GradientIndexing(&doflist1[0],control_index);
@@ -3518,5 +3516,5 @@
 			break;
 		default:
-			_error2_("control type not supported yet: " << control_type);
+			_error_("control type not supported yet: " << control_type);
 	}
 
@@ -3548,5 +3546,5 @@
 			break;
 		default:
-			_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 	}
 
@@ -4087,5 +4085,5 @@
 		 *      S                obs            obs
 		 */
-		misfit=1/S*pow( pow(vx-vxobs,2.) + pow(vy-vyobs,2.) ,0.5);
+		misfit=1/S*sqrt( pow(vx-vxobs,2) + pow(vy-vyobs,2));
 
 		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
@@ -4150,7 +4148,7 @@
 		 *                            obs
 		 */
-		velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
-		obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
-		misfit=4*pow(meanvel,2.)*pow(log(velocity_mag/obs_velocity_mag),2.);
+		velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+		obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+		misfit=4*pow(meanvel,2)*pow(log(velocity_mag/obs_velocity_mag),2);
 
 		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVelMisfitEnum);
@@ -4216,7 +4214,7 @@
 		 *                              obs                       obs
 		 */
-		misfit=0.5*pow(meanvel,2.)*(
-					pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2.) +
-					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2.) );
+		misfit=0.5*pow(meanvel,2)*(
+					pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2) +
+					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2) );
 
 		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVxVyMisfitEnum);
@@ -4279,5 +4277,5 @@
 		 *
 		 */
-		misfit=0.5*( pow(vx-vxobs,2.) + pow(vy-vyobs,2.) );
+		misfit=0.5*( pow(vx-vxobs,2) + pow(vy-vyobs,2) );
 
 		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
@@ -4342,7 +4340,7 @@
 		 *              obs                        obs                      
 		 */
-		scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
-		scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
-		misfit=0.5*(scalex*pow((vx-vxobs),2.)+scaley*pow((vy-vyobs),2.));
+		scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+		scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+		misfit=0.5*(scalex*pow((vx-vxobs),2)+scaley*pow((vy-vyobs),2));
 		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceRelVelMisfitEnum);
 
@@ -4392,5 +4390,5 @@
 
 		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
-		Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
 	}
 
@@ -4410,5 +4408,5 @@
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  dp[NDOF2];
-	IssmDouble  vx,vy;
+	IssmDouble  vx,vy,vel;
 	GaussTria  *gauss                    = NULL;
 
@@ -4439,4 +4437,7 @@
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
 
 		/*J = 1/2 ( vx*dH/dx + vy*dH/dy )^2 */
@@ -4459,5 +4460,5 @@
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  dp[NDOF2];
-	IssmDouble  vx,vy;
+	IssmDouble  vx,vy,vel;
 	GaussTria  *gauss                    = NULL;
 
@@ -4488,4 +4489,7 @@
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
 
 		/*J = 1/2 ( -vy*dH/dx + vx*dH/dy )^2 */
@@ -4535,5 +4539,5 @@
 
 		/*compute ThicknessAbsMisfit*/
-		Jelem+=0.5*pow(thickness-thicknessobs,2.0)*weight*Jdet*gauss->weight;
+		Jelem+=0.5*(thickness-thicknessobs)*(thickness-thicknessobs)*weight*Jdet*gauss->weight;
 	}
 
@@ -4558,5 +4562,5 @@
 	IssmDouble  dbasis[NDOF2][NUMVERTICES];
 	IssmDouble  dH[2];
-	IssmDouble  v[2];
+	IssmDouble  vx,vy,vel;
 	GaussTria *gauss     = NULL;
 	int       *responses = NULL;
@@ -4603,16 +4607,22 @@
 			case ThicknessAlongGradientEnum:
 				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&v[0],gauss);
-				vy_input->GetInputValue(&v[1],gauss);
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*v[0]+dH[1]*v[1])*(dbasis[0][i]*v[0]+dbasis[1][i]*v[1])*Jdet*gauss->weight;
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
 				break;
 			case ThicknessAcrossGradientEnum:
 				weights_input->GetInputValue(&weight, gauss,resp);
-				vx_input->GetInputValue(&v[0],gauss);
-				vy_input->GetInputValue(&v[1],gauss);
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*(-v[1])+dH[1]*v[0])*(dbasis[0][i]*(-v[1])+dbasis[1][i]*v[0])*Jdet*gauss->weight;
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
 				break;
 			default:
-				_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 		}
 	}
@@ -4717,6 +4727,6 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
-						scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
+						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
 						dux=scalex*(vxobs-vx);
 						duy=scaley*(vyobs-vy);
@@ -4738,7 +4748,7 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
-						obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
-						scale=-8*pow(meanvel,2.)/pow(velocity_mag,2.)*log(velocity_mag/obs_velocity_mag);
+						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
 						dux=scale*vx;
 						duy=scale*vy;
@@ -4758,5 +4768,5 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						scale=1./(S*2*sqrt(pow(vx-vxobs,2.)+pow(vy-vyobs,2.))+epsvel);
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
 						dux=scale*(vxobs-vx);
 						duy=scale*(vyobs-vy);
@@ -4776,6 +4786,6 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						dux = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
-						duy = - pow(meanvel,2.) * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
 						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
 						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
@@ -4798,5 +4808,5 @@
 					break;
 				default:
-					_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 			}
 		}
@@ -4900,6 +4910,6 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
-						scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
+						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
 						dux=scalex*(vxobs-vx);
 						duy=scaley*(vyobs-vy);
@@ -4921,7 +4931,7 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
-						obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
-						scale=-8*pow(meanvel,2.)/pow(velocity_mag,2.)*log(velocity_mag/obs_velocity_mag);
+						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
 						dux=scale*vx;
 						duy=scale*vy;
@@ -4941,5 +4951,5 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						scale=1./(S*2*sqrt(pow(vx-vxobs,2.)+pow(vy-vyobs,2.))+epsvel);
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
 						dux=scale*(vxobs-vx);
 						duy=scale*(vyobs-vy);
@@ -4959,6 +4969,6 @@
 					 */
 					for (i=0;i<NUMVERTICES;i++){
-						dux = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
-						duy = - pow(meanvel,2.) * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
 						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
 						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
@@ -4981,5 +4991,5 @@
 					break;
 				default:
-					_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 			}
 		}
@@ -5028,5 +5038,5 @@
 
 		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
-		Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
 	}
 
@@ -5050,5 +5060,5 @@
 			break;
 		default:
-			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
 	}
 
@@ -5151,6 +5161,6 @@
 
 		/*Check solution*/
-		if(xIsNan<IssmDouble>(lambdax[i])) _error2_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambday[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
 	}
 
@@ -5182,5 +5192,5 @@
 	for(i=0;i<numdof;i++){
 		lambda[i]=values[i];
-		if(xIsNan<IssmDouble>(lambda[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambda[i])) _error_("NaN found in solution vector");
 	}
 
@@ -5205,5 +5215,5 @@
 
 	/*Get input (either in element or material)*/
-	if(control_enum==MaterialsRheologyBbarEnum){
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
 		input=(Input*)matice->inputs->GetInput(control_enum); _assert_(input);
 	}
@@ -5214,5 +5224,5 @@
 	/*Check that it is a ControlInput*/
 	if (input->ObjectEnum()!=ControlInputEnum){
-		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
 
@@ -5240,5 +5250,5 @@
 	new_input = new TriaP1Input(control_enum,values);
 
-	if(control_enum==MaterialsRheologyBbarEnum){
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
 		input=(Input*)matice->inputs->GetInput(control_enum); _assert_(input);
 	}
@@ -5248,5 +5258,5 @@
 
 	if (input->ObjectEnum()!=ControlInputEnum){
-		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
 
@@ -5285,5 +5295,5 @@
 
 	/* compute VelocityFactor */
-	VelocityFactor= n_man*pow(CR,2)*rho_water*g/mu_water;
+	VelocityFactor= n_man*CR*CR*rho_water*g/mu_water;
 	
 	gauss=new GaussTria();
@@ -5297,9 +5307,8 @@
 
 		/* Water velocity x and y components */
-	//	vx[iv]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
-	//	vy[iv]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
-	
-		vx[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
-		vy[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	//	vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+	//	vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+		vx[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
 	}
 
@@ -5396,5 +5405,5 @@
 
 		/*Artificial diffusivity*/
-		vel=sqrt(pow(vx,2.)+pow(vy,2.));
+		vel=sqrt(vx*vx+vy*vy);
 		K[0][0]=diffusivity*h/(2*vel)*vx*vx;
 		K[1][0]=diffusivity*h/(2*vel)*vy*vx;
@@ -5457,5 +5466,5 @@
 		old_watercolumn_input->GetInputValue(&old_watercolumn_g,gauss);
 
-		if(dt)for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
+		if(reCast<int,IssmDouble>(dt))for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
 		else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
 	}
@@ -5506,9 +5515,7 @@
 
 	/*Intermediaries*/
-	const int numdof = NDOF1*NUMVERTICES;
-
-	int       i;
-	int*      doflist=NULL;
-	IssmDouble    values[numdof];
+	const int   numdof         = NDOF1 *NUMVERTICES;
+	int        *doflist        = NULL;
+	IssmDouble  values[numdof];
 
 	/*Get dof list: */
@@ -5516,9 +5523,8 @@
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof;i++){
+	for(int i=0;i<numdof;i++){
 		values[i]=solution[doflist[i]];
-		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
-		if (values[i]<pow((IssmDouble)10,(IssmDouble)-10))values[i]=pow((IssmDouble)10,(IssmDouble)-10); //correcting the water column to positive values
- 
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		if (values[i]<10e-10) values[i]=10e-10; //correcting the water column to positive values
 	}
 
@@ -5617,5 +5623,5 @@
 
 		default:
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 
@@ -5624,10 +5630,10 @@
 /*FUNCTION Tria::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
 void  Tria::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
 /*FUNCTION Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
 void  Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 }
 /*}}}*/
@@ -5671,5 +5677,5 @@
 
 		default:
-			_error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 
@@ -5688,5 +5694,5 @@
 			return CreateKMatrixBalancethickness_DG();
 		default:
-			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
 	}
 
@@ -5771,5 +5777,5 @@
 		if(stabilization==1){
 			/*Streamline upwinding*/
-			vel=sqrt(pow(vx,2.)+pow(vy,2.));
+			vel=sqrt(vx*vx+vy*vy);
 			K[0][0]=h/(2*vel)*vx*vx;
 			K[1][0]=h/(2*vel)*vy*vx;
@@ -5867,5 +5873,5 @@
 			return CreatePVectorBalancethickness_DG();
 		default:
-			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
 	}
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h	(revision 13101)
@@ -100,5 +100,5 @@
 		void   InputToResult(int enum_type,int step,IssmDouble time);
 		void   DeleteResults(void);
-		void   MaterialUpdateFromTemperature(void){_error2_("not implemented yet");};
+		void   MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
 		void   MigrateGroundingLine(IssmDouble* oldfloating,IssmDouble* sheet_ungrounding);
 		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units);
@@ -110,5 +110,5 @@
 		void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
 		void   ProcessResultsUnits(void);
-		void   ResetCoordinateSystem(void){_error2_("not implemented yet");};
+		void   ResetCoordinateSystem(void){_error_("not implemented yet");};
 		void	 SmbGradients();
 		IssmDouble SurfaceArea(void);
@@ -179,5 +179,5 @@
 		ElementMatrix* CreateKMatrixPrognostic_CG(void);
 		ElementMatrix* CreateKMatrixPrognostic_DG(void);
-		ElementMatrix* CreateKMatrixSlope(void);
+		ElementMatrix* CreateMassMatrix(void);
 		ElementVector* CreatePVectorBalancethickness(void);
 		ElementVector* CreatePVectorBalancethickness_DG(void);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13101)
@@ -338,5 +338,5 @@
 
 	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.));
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
@@ -353,5 +353,5 @@
 	/*Get Determinant*/
 	Matrix2x2Determinant(Jdet,&J[0][0]);
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
@@ -375,5 +375,5 @@
 
 	*Jdet=SQRT3/6.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
-	if(*Jdet<0) _error2_("negative jacobian determinant!");
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13101)
@@ -112,20 +112,20 @@
 /*}}}*/
 /*FUNCTION BoolInput::GetInputValue(int* pvalue){{{*/
-void BoolInput::GetInputValue(int* pvalue){_error2_("not supported yet!");}
+void BoolInput::GetInputValue(int* pvalue){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue){{{*/
-void BoolInput::GetInputValue(IssmDouble* pvalue){_error2_("not supported yet!");}
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
-void BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not supported yet!");}
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
-void BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not supported yet!");}
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
-void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not supported yet!");}
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not supported yet!");}
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION BoolInput::ChangeEnum{{{*/
@@ -161,5 +161,5 @@
 
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 
@@ -176,5 +176,5 @@
 void BoolInput::GetVectorFromInputs(Vector* vector,int* doflist){
 
-	_error2_("not supporte yet!");
+	_error_("not supporte yet!");
 
 }
@@ -183,5 +183,5 @@
 void BoolInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
 
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h	(revision 13101)
@@ -37,10 +37,10 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
 		ElementResult* SpawnResult(int step, IssmDouble time);
 		void Configure(Parameters* parameters);
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		/*}}}*/
 		/*numerics: {{{*/
@@ -50,32 +50,32 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetInputAverage(IssmDouble* pvalue){_error2_("not implemented yet");};
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
-		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
-		IssmDouble InfinityNorm(void){_error2_("InfinityNorm not implemented for booleans");};
-		IssmDouble Max(void){_error2_("Max not implemented for booleans");};
-		IssmDouble MaxAbs(void){_error2_("Max not implemented for booleans");};
-		IssmDouble Min(void){_error2_("Min not implemented for booleans");};
-		IssmDouble MinAbs(void){_error2_("Min not implemented for booleans");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		IssmDouble Max(void){_error_("Max not implemented for booleans");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for booleans");};
+		IssmDouble Min(void){_error_("Min not implemented for booleans");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for booleans");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error2_("Constrain not implemented for booleans");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
 		void Extrude(void);
-		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector* vector,int* doflist);
 		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13101)
@@ -48,5 +48,5 @@
 			break;
 		default:
-			_error2_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
+			_error_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
 	}
 	gradient   =NULL;
@@ -152,5 +152,5 @@
 /*FUNCTION ControlInput::ScaleGradient{{{*/
 void ControlInput::ScaleGradient(IssmDouble scaling_factor){
-	if(!gradient) _error2_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
+	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
 	gradient->Scale(scaling_factor);
 }/*}}}*/
@@ -170,5 +170,5 @@
 			break;
 		default:
-			_error2_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
+			_error_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
 	}
 
@@ -221,5 +221,5 @@
 	 }
 	 else{
-		 _error2_("Data " << data << " not supported yet");
+		 _error_("Data " << data << " not supported yet");
 	 }
 }/*}}}*/
@@ -258,5 +258,5 @@
 /*FUNCTION ControlInput::SaveValue{{{*/
 void ControlInput::SaveValue(void){
-	if(!values) _error2_("Values of " << EnumToStringx(this->enum_type) << " not found");
+	if(!values) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
 
 	if(savedvalues) delete this->savedvalues;
@@ -265,6 +265,6 @@
 /*FUNCTION ControlInput::UpdateValue{{{*/
 void ControlInput::UpdateValue(IssmDouble scalar){
-	if(!gradient)    _error2_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
-	if(!savedvalues) _error2_("Values of " << EnumToStringx(this->enum_type) << " not found");
+	if(!gradient)    _error_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
+	if(!savedvalues) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
 
 	if(values) delete this->values;
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h	(revision 13101)
@@ -41,9 +41,9 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		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){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
@@ -55,36 +55,36 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetInputAverage(IssmDouble* pvalue);
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void ChangeEnum(int newenumtype){_error2_("not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error2_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
-		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
-		void AXPY(Input* xinput,IssmDouble scalar){_error2_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
 		void Constrain(void);
 		void Constrain(IssmDouble min,IssmDouble max);
-		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
-		IssmDouble Max(void){_error2_("not implemented yet");};
-		IssmDouble MaxAbs(void){_error2_("not implemented yet");};
-		IssmDouble Min(void){_error2_("not implemented yet");};
-		IssmDouble MinAbs(void){_error2_("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);
 		void VerticallyIntegrate(Input* thickness_input);
 		void GetVectorFromInputs(Vector* vector,int* doflist,const char* data);
 		void GetVectorFromInputs(Vector* vector,int* doflist);
-		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not implemented yet");};
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not implemented yet");};
 		ElementResult* SpawnGradient(int step, IssmDouble time);
 		void GetGradient(Vector* gradient_vec,int* doflist);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13101)
@@ -115,5 +115,5 @@
 
 	/*Get requested input within dataset*/
-	if(index<0 || index > inputs->Size()-1) _error2_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
+	if(index<0 || index > inputs->Size()-1) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
 	Input* input=(Input*)this->inputs->GetObjectByOffset(index);
 	
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h	(revision 13101)
@@ -37,54 +37,54 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
-		ElementResult* SpawnResult(int step, IssmDouble time){_error2_("not implemented yet");};
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time){_error_("not implemented yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
 		/*numerics: {{{*/
-		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index);
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetInputAverage(IssmDouble* pvalue){_error2_("not implemented yet");};
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void ChangeEnum(int newenumtype){_error2_("not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error2_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
-		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
-		void AXPY(Input* xinput,IssmDouble scalar){_error2_("not implemented yet");};
-		void Constrain(void){_error2_("not implemented yet");};
-		void Constrain(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
-		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
-		IssmDouble Max(void){_error2_("not implemented yet");};
-		IssmDouble MaxAbs(void){_error2_("not implemented yet");};
-		IssmDouble Min(void){_error2_("not implemented yet");};
-		IssmDouble MinAbs(void){_error2_("not implemented yet");};
-		void Extrude(void){_error2_("not implemented yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error2_("not implemented yet");};
-		void GetVectorFromInputs(Vector* vector,int* doflist){_error2_("not implemented yet");};
-		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not implemented yet");};
-		ElementResult* SpawnGradient(int step, IssmDouble time){_error2_("not implemented yet");};
-		void GetGradient(Vector* gradient_vec,int* doflist){_error2_("not implemented yet");};
-		void ScaleGradient(IssmDouble scale){_error2_("not implemented yet");};
-		void SetGradient(Input* gradient_in){_error2_("not implemented yet");};
-		void UpdateValue(IssmDouble scalar){_error2_("not implemented yet");};
-		void SaveValue(void){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(void){_error_("not implemented yet");};
+		void Constrain(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist){_error_("not implemented yet");};
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time){_error_("not implemented yet");};
+		void GetGradient(Vector* gradient_vec,int* doflist){_error_("not implemented yet");};
+		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
+		void UpdateValue(IssmDouble scalar){_error_("not implemented yet");};
+		void SaveValue(void){_error_("not implemented yet");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13101)
@@ -108,5 +108,5 @@
 /*FUNCTION DoubleInput::GetInputValue(bool* pvalue) {{{*/
 void DoubleInput::GetInputValue(bool* pvalue){
-	_error2_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
+	_error_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
 
 }
@@ -114,5 +114,5 @@
 /*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{*/
 void DoubleInput::GetInputValue(int* pvalue){
-	_error2_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+	_error_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
 
 }
@@ -132,8 +132,8 @@
 /*}}}*/
 /*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
-void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not supported yet!");}
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not supported yet!");}
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION DoubleInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){{{*/
@@ -217,5 +217,5 @@
 
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 
@@ -253,5 +253,5 @@
 void DoubleInput::GetVectorFromInputs(Vector* vector,int* doflist){
 
-	_error2_("not supporte yet!");
+	_error_("not supporte yet!");
 
 }
@@ -260,5 +260,5 @@
 void DoubleInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
 
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 
 }
@@ -276,5 +276,5 @@
 
 	/*Check that input provided is a thickness*/
-	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error2_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
 
 	/*vertically integrate depending on type:*/
@@ -287,5 +287,5 @@
 
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13101)
@@ -40,5 +40,5 @@
 		Input* PointwiseMax(Input* inputB);
 		ElementResult* SpawnResult(int step, IssmDouble time);
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
@@ -49,8 +49,8 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -67,13 +67,13 @@
 		void ConstrainMin(IssmDouble minimum);
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void){_error2_("not supported yet");};
+		void Extrude(void){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input);
 		void GetVectorFromInputs(Vector* vector,int* doflist);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13101)
@@ -99,5 +99,5 @@
 ElementResult* IntInput::SpawnResult(int step, IssmDouble time){
 	
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 
 }
@@ -106,5 +106,5 @@
 /*Object functions*/
 /*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{*/
-void IntInput::GetInputValue(bool* pvalue){_error2_("not supported yet!");}
+void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION IntInput::GetInputValue(int* pvalue){{{*/
@@ -115,18 +115,18 @@
 /*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue){{{*/
 void IntInput::GetInputValue(IssmDouble* pvalue){
-	_error2_("IntInput cannot return a IssmDouble in parallel");
+	_error_("IntInput cannot return a IssmDouble in parallel");
 }
 /*}}}*/
 /*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
-void IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not supported yet!");}
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
-void IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not supported yet!");}
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
-void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not supported yet!");}
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not supported yet!");}
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
 /*}}}*/
 /*FUNCTION IntInput::ChangeEnum{{{*/
@@ -166,5 +166,5 @@
 
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 
@@ -182,5 +182,5 @@
 void IntInput::GetVectorFromInputs(Vector* vector,int* doflist){
 
-	_error2_("not supporte yet!");
+	_error_("not supporte yet!");
 
 }
@@ -189,5 +189,5 @@
 void IntInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
 
-	_error2_("not supported yet!");
+	_error_("not supported yet!");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h	(revision 13101)
@@ -37,9 +37,9 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		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){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
@@ -50,32 +50,32 @@
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetInputAverage(IssmDouble* pvalue){_error2_("not implemented yet");};
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
-		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		IssmDouble InfinityNorm(void){_error2_("InfinityNorm not implemented for integers");};
-		IssmDouble Max(void){_error2_("Max not implemented for integers");};
-		IssmDouble MaxAbs(void){_error2_("Max not implemented for integers");};
-		IssmDouble Min(void){_error2_("Min not implemented for integers");};
-		IssmDouble MinAbs(void){_error2_("Min not implemented for integers");};
-		void Extrude(void){_error2_("not supported yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for integers");};
+		IssmDouble Max(void){_error_("Max not implemented for integers");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for integers");};
+		IssmDouble Min(void){_error_("Min not implemented for integers");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for integers");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector* vector,int* doflist);
 		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13101)
@@ -455,10 +455,10 @@
 		case ControlInputEnum:{
 			ControlInput* cont_input=(ControlInput*)xinput;
-			if(cont_input->values->ObjectEnum()!=PentaP1InputEnum) _error2_("not supported yet");
+			if(cont_input->values->ObjectEnum()!=PentaP1InputEnum) _error_("not supported yet");
 			PentaP1Input* cast_input=(PentaP1Input*)cont_input->values;
 			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
 			return;
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 
@@ -495,5 +495,5 @@
 
 	/*Check that input provided is a thickness*/
-	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error2_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
 
 	/*Get Thickness value pointer*/
@@ -511,5 +511,5 @@
 
 		default:
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 }
@@ -529,5 +529,5 @@
 
 	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(PentaP1Input*)inputB;
 
@@ -560,5 +560,5 @@
 
 	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(PentaP1Input*)inputB;
 
@@ -591,5 +591,5 @@
 
 	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(PentaP1Input*)inputB;
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13101)
@@ -41,22 +41,22 @@
 		Input* PointwiseMax(Input* inputB);
 		ElementResult* SpawnResult(int step, IssmDouble time);
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
 		/*numerics: {{{*/
-		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetInputAverage(IssmDouble* pvalue);
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("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);
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
@@ -69,5 +69,5 @@
 		void ConstrainMin(IssmDouble minimum);
 		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13101)
@@ -482,5 +482,5 @@
 		}
 	}
-	if(!found)_error2_("did not find time interval on which to interpolate forcing values!");
+	if(!found)_error_("did not find time interval on which to interpolate forcing values!");
 
 	/*Assign output pointer*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h	(revision 13101)
@@ -40,38 +40,38 @@
 		int    InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* forcingB){_error2_("not implemented yet");};
-		Input* PointwiseMin(Input* forcingB){_error2_("not implemented yet");};
-		Input* PointwiseMax(Input* forcingB){_error2_("not implemented yet");};
+		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
 		ElementResult* SpawnResult(int step, IssmDouble time);
 		void Configure(Parameters* parameters);
 		/*}}}*/
 		/*numerics: {{{*/
-		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time);
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetInputAverage(IssmDouble* pvalue);
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 
 		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
-		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
-		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
-		void AXPY(Input* xforcing,IssmDouble scalar){_error2_("not implemented yet");};
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error2_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
 		IssmDouble InfinityNorm(void);
 		IssmDouble Max(void);
@@ -80,8 +80,8 @@
 		IssmDouble MinAbs(void);
 		void Extrude(void);
-		void VerticallyIntegrate(Input* thickness_forcing){_error2_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector* vector,int* doflist);
-		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not supported yet");};
-      void GetTimeValues(IssmDouble* values,IssmDouble time){_error2_("not implemented yet");};
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not supported yet");};
+      void GetTimeValues(IssmDouble* values,IssmDouble time){_error_("not implemented yet");};
 		Input* GetTimeInput(IssmDouble time);
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13101)
@@ -323,5 +323,5 @@
 
 		default :
-			_error2_("not implemented yet");
+			_error_("not implemented yet");
 	}
 
@@ -368,5 +368,5 @@
 
 	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaP1Input*)inputB;
 
@@ -399,5 +399,5 @@
 
 	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaP1Input*)inputB;
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13101)
@@ -37,31 +37,31 @@
 		int   InstanceEnum();
 		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB);
 		Input* PointwiseMax(Input* inputB);
 		ElementResult* SpawnResult(int step, IssmDouble time);
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
 		/*}}}*/
 		/*numerics: {{{*/
-		void GetInputValue(bool* pvalue){_error2_("not implemented yet");}
-		void GetInputValue(int* pvalue){_error2_("not implemented yet");}
-		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");}
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){_error2_("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, GaussTria* gauss);
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetInputAverage(IssmDouble* pvalue);
 		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss);
 		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss);
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 
@@ -77,6 +77,6 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void){_error2_("not supported yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector* vector,int* doflist);
 		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13101)
@@ -259,5 +259,5 @@
 
 	if (strncmp(&ktag[0],"<"        ,1) || strncmp(&ktag[strlen(ktag)-1],">",1))
-		_error2_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
+		_error_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
 
 /*  strtok modifies ktag, so work on copy  */
@@ -355,5 +355,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-		_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
 
 	sscanf(kstr,"%d",pival);
@@ -368,5 +368,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -388,5 +388,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-	  {_error2_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
+	  {_error_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
 
 	sscanf(kstr,"%d",&ival);
@@ -402,5 +402,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -433,5 +433,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-		_error2_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
+		_error_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
 
 	if (!pstr) {
@@ -463,5 +463,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -484,5 +484,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-	  {_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
+	  {_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
 
 	sscanf(kstr,"%g",pfval);
@@ -497,5 +497,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -518,5 +518,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-		_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
 
 	sscanf(kstr,"%lg",pdval);
@@ -531,5 +531,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -556,5 +556,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-		_error2_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
+		_error_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
 
 	if (!*pdval)
@@ -570,5 +570,5 @@
 		i++;
 		if (maxlen && (maxlen < i+1))
-			_error2_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
+			_error_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
 		sscanf(ktok,"%lg",&((*pdval)[i]));
 		ktok=strtok(NULL,delim);
@@ -595,5 +595,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -622,5 +622,5 @@
 							NULL,NULL)) ||
 		(kstr[0] == '<'))
-		_error2_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
+		_error_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
 
 	if (!*pdval)
@@ -636,5 +636,5 @@
 		i++;
 		if (maxlen && (maxlen*n < i+1))
-			_error2_("KMLFileTokenParse -- Double [m x n] field too short for " << ktag << ".\n");
+			_error_("KMLFileTokenParse -- Double [m x n] field too short for " << ktag << ".\n");
 		j=(j+1) % n;
 		sscanf(ktok,"%lg",&((*pdval)[i]));
@@ -665,5 +665,5 @@
 			(kstr[1] != '/') ||
 			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
-		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
 		else
 			xDelete<char>(kstr);
@@ -712,5 +712,5 @@
 		else if ((kstr[0] == '<') &&
 				 (kstr[1] == '/')) {
-			_error2_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
+			_error_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
 		}
 
@@ -718,5 +718,5 @@
 	}
 
-	_error2_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
+	_error_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
 
 	return(0);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h	(revision 13101)
@@ -30,11 +30,11 @@
 		virtual void  DeepEcho();
 		virtual void  DeepEcho(const char* indent);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 13101)
@@ -93,7 +93,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
+	  {_error_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_ColorStyle::Read -- Unexpected field \"" << kstr << "\"");}
+	  {_error_("KML_ColorStyle::Read -- Unexpected field \"" << kstr << "\"");}
 
 	else if (!strcmp(kstr,"<color>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13101)
@@ -35,11 +35,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h	(revision 13101)
@@ -30,11 +30,11 @@
 		virtual void  DeepEcho();
 		virtual void  DeepEcho(const char* indent);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp	(revision 13101)
@@ -120,7 +120,7 @@
 	}
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_Container::Read -- Unexpected closing tag " << kstr );}
+	  {_error_("KML_Container::Read -- Unexpected closing tag " << kstr );}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_Container::Read -- Unexpected field \"" << kstr << "\"");}
+	  {_error_("KML_Container::Read -- Unexpected field \"" << kstr << "\"");}
 
 	else if (!strncmp(kstr,"<Placemark",10)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h	(revision 13101)
@@ -33,11 +33,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp	(revision 13101)
@@ -106,7 +106,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strncmp(kstri,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h	(revision 13101)
@@ -30,11 +30,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp	(revision 13101)
@@ -149,7 +149,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
+	  {_error_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_Feature::Read -- Unexpected field \"" << kstr << "\"");}
+	  {_error_("KML_Feature::Read -- Unexpected field \"" << kstr << "\"");}
 
 	else if (!strncmp(kstr,"<Style", 6)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h	(revision 13101)
@@ -44,11 +44,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp	(revision 13101)
@@ -107,7 +107,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
+		  {_error_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
+		  {_error_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
 
 		else if (!strncmp(kstri,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h	(revision 13101)
@@ -31,11 +31,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp	(revision 13101)
@@ -106,7 +106,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strncmp(kstri,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h	(revision 13101)
@@ -30,11 +30,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 13101)
@@ -79,7 +79,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
+	  {_error_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
+	  {_error_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
 
 	else if (!strncmp(kstr,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h	(revision 13101)
@@ -29,11 +29,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 13101)
@@ -131,7 +131,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_GroundOverlay::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_GroundOverlay::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<altitude>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13101)
@@ -36,11 +36,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp	(revision 13101)
@@ -145,7 +145,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Icon::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Icon::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<href>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h	(revision 13101)
@@ -44,11 +44,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 13101)
@@ -121,7 +121,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_LatLonBox::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_LatLonBox::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<north>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13101)
@@ -35,11 +35,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp	(revision 13101)
@@ -141,7 +141,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_LineString::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_LineString::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<extrude>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h	(revision 13101)
@@ -38,11 +38,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 13101)
@@ -113,7 +113,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_LineStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_LineStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<width>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13101)
@@ -31,11 +31,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 13101)
@@ -139,7 +139,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_LinearRing::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_LinearRing::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<extrude>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13101)
@@ -38,11 +38,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 13101)
@@ -140,7 +140,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_MultiGeometry::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_MultiGeometry::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strncmp(kstri,"<Point", 6)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13101)
@@ -34,11 +34,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp	(revision 13101)
@@ -146,7 +146,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
+	  {_error_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_Object::Read -- Unexpected field \"" << kstr << "\".\n");}
+	  {_error_("KML_Object::Read -- Unexpected field \"" << kstr << "\".\n");}
 
 	else if (!strncmp(kstr,"<Placemark",10)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h	(revision 13101)
@@ -31,11 +31,11 @@
 		virtual void  DeepEcho();
 		virtual void  DeepEcho(const char* indent);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 13101)
@@ -110,7 +110,7 @@
 	}
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
+	  {_error_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_Overlay::Read -- Unexpected field \"" << kstr << "\".\n");}
+	  {_error_("KML_Overlay::Read -- Unexpected field \"" << kstr << "\".\n");}
 
 	else if (!strcmp(kstr,"<color>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h	(revision 13101)
@@ -36,11 +36,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 13101)
@@ -140,7 +140,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Placemark::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Placemark::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strncmp(kstri,"<Point", 6)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h	(revision 13101)
@@ -34,11 +34,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp	(revision 13101)
@@ -126,7 +126,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Point::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Point::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<extrude>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h	(revision 13101)
@@ -36,11 +36,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 13101)
@@ -117,7 +117,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_PolyStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_PolyStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<fill>"))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13101)
@@ -32,11 +32,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 13101)
@@ -179,7 +179,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Polygon::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 		else if (!strcmp(kstri,"<extrude>"))
@@ -207,7 +207,7 @@
 				}
 				else if (!strncmp(kstrj,"</",2))
-				  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
 				else if (strncmp(kstrj,"<",1))
-				  {_error2_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
 
 				else if (!strncmp(kstrj,"<LinearRing",11)) {
@@ -234,7 +234,7 @@
 				}
 				else if (!strncmp(kstrj,"</",2))
-				  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
 				else if (strncmp(kstrj,"<",1))
-				  {_error2_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
 
 				else if (!strncmp(kstrj,"<LinearRing",11)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h	(revision 13101)
@@ -40,11 +40,11 @@
 		void  Read(FILE* fid,char* kstr);
 		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp	(revision 13101)
@@ -189,7 +189,7 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
 		else if (strncmp(kstri,"<",1))
-		  {_error2_("KML_Style::Read -- Unexpected field \"" << kstri << "\".\n");}
+		  {_error_("KML_Style::Read -- Unexpected field \"" << kstri << "\".\n");}
 
 //		else if (!strncmp(kstri,"<IconStyle",10)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h	(revision 13101)
@@ -38,11 +38,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 13101)
@@ -83,7 +83,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
+	  {_error_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
+	  {_error_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
 
 	else if (!strncmp(kstr,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13101)
@@ -29,11 +29,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 13101)
@@ -83,7 +83,7 @@
 		return;
 	else if (!strncmp(kstr,"</",2))
-	  {_error2_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
+	  {_error_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
 	else if (strncmp(kstr,"<",1))
-	  {_error2_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
+	  {_error_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
 
 	else if (!strncmp(kstr,"<",1))
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13101)
@@ -29,11 +29,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 13101)
@@ -160,5 +160,5 @@
 		}
 		else if (!strncmp(kstri,"</",2))
-		  {_error2_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
+		  {_error_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
 
 		else if (strncmp(kstri,"<",1)) {
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h	(revision 13101)
@@ -32,11 +32,11 @@
 		void  Write(FILE* fid,const char* indent);
 		void  Read(FILE* fid,char* kstr);
-		int   Id(){_error2_("Not implemented yet.");};
-		int   MyRank(){_error2_("Not implemented yet.");};
-		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   MarshallSize(){_error2_("Not implemented yet.");};
-		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
-		int   ObjectEnum(){_error2_("Not implemented yet.");};
-		Object* copy(){_error2_("Not implemented yet.");};
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp	(revision 13101)
@@ -107,8 +107,8 @@
 		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
 	}
-	else _error2_("element_type "<< element_type << " not supported yet");
+	else _error_("element_type "<< element_type << " not supported yet");
 
 	/*Checks that s-1>0 if v=0*/
-        if(vmag==0 && (s-1)<0) _error2_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+        if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
 
 	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
@@ -171,8 +171,8 @@
 		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
 	}
-	else _error2_("element_type "<< element_type << " not supported yet");
+	else _error_("element_type "<< element_type << " not supported yet");
 
 	/*Checks that s-1>0 if v=0*/
-	if(vmag==0 && (s-1)<0) _error2_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
 
 	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
@@ -238,8 +238,8 @@
 		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
 	}
-	else _error2_("element_type "<< element_type << " not supported yet");
+	else _error_("element_type "<< element_type << " not supported yet");
 
 	/*Checks that s-1>0 if v=0*/
-	if(vmag==0 && (s-1)<0) _error2_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
 
 	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
@@ -304,8 +304,8 @@
 		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
 	}
-	else _error2_("element_type "<< element_type << " not supported yet");
+	else _error_("element_type "<< element_type << " not supported yet");
 
 	/*Checks that s-1>0 if v=0*/
-	if(vmag==0 && (s-1)<0) _error2_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
 
 	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
@@ -319,5 +319,5 @@
 
 	Input* input=inputs->GetInput(enum_type);
-	if(!input) _error2_("input " << EnumToStringx(enum_type) << " not found");
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
 	input->GetInputValue(pvalue,gauss);
 
@@ -328,5 +328,5 @@
 
 	Input* input=inputs->GetInput(enum_type);
-	if(!input) _error2_("input " << EnumToStringx(enum_type) << " not found");
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
 	input->GetInputValue(pvalue,gauss);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp	(revision 13101)
@@ -81,5 +81,5 @@
 		icefront_node_ids[3]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+3));
 	}
-	else _error2_("in_icefront_type " << EnumToStringx(in_icefront_type) << " not supported yet!");
+	else _error_("in_icefront_type " << EnumToStringx(in_icefront_type) << " not supported yet!");
 
 	if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum)
@@ -263,5 +263,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -379,5 +379,5 @@
 	    #endif
 		default:
-			_error2_("Icefront type " << EnumToStringx(type) << " not supported yet");
+			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
 	}
 }
@@ -441,5 +441,5 @@
 				break;
 			default:
-				_error2_("fill type " << EnumToStringx(fill) << " not supported yet");
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
 		}
 		ice_pressure=1.0/2.0*gravity*rho_ice*pow(thickness,2);
@@ -564,5 +564,5 @@
 				break;
 			default:
-				_error2_("fill type " << EnumToStringx(fill) << " not supported yet");
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
 		}
 		ice_pressure=rho_ice*gravity*(surface-z_g);
@@ -638,5 +638,5 @@
 				break;
 			default:
-				_error2_("fill type " << EnumToStringx(fill) << " not supported yet");
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
 		}
 		air_pressure=0;
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h	(revision 13101)
@@ -64,5 +64,5 @@
 		void  InputUpdateFromConstant(bool constant, int name);
 		void  InputUpdateFromSolution(IssmDouble* solution);
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13101)
@@ -270,5 +270,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -300,5 +300,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -347,5 +347,5 @@
 			return CreateKMatrixPrognosticBoundary();
 		default:
-			_error2_("type not supported yet");
+			_error_("type not supported yet");
 	}
 }
@@ -500,5 +500,5 @@
 			return CreateKMatrixBalancethicknessBoundary();
 		default:
-			_error2_("type not supported yet");
+			_error_("type not supported yet");
 	}
 }
@@ -651,5 +651,5 @@
 			return CreateKMatrixAdjointBalancethicknessBoundary();
 		default:
-			_error2_("type not supported yet");
+			_error_("type not supported yet");
 	}
 }
@@ -683,5 +683,5 @@
 			return CreatePVectorPrognosticBoundary();
 		default:
-			_error2_("type not supported yet");
+			_error_("type not supported yet");
 	}
 }
@@ -751,5 +751,5 @@
 		vyaverage_input->GetInputValue(&vy,gauss);
 		spcthickness_input->GetInputValue(&thickness,gauss);
-		if(xIsNan<IssmDouble>(thickness)) _error2_("Cannot weakly apply constraint because NaN was provided");
+		if(xIsNan<IssmDouble>(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
 
 		UdotN=vx*normal[0]+vy*normal[1];
@@ -777,5 +777,5 @@
 			return CreatePVectorBalancethicknessBoundary();
 		default:
-			_error2_("type not supported yet");
+			_error_("type not supported yet");
 	}
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h	(revision 13101)
@@ -50,15 +50,15 @@
 		/*Update virtual functions resolution: {{{*/
 		void    InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
-		void    InputUpdateFromVector(int* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVector(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
 		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*Do nothing*/}
-		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void    InputUpdateFromConstant(IssmDouble constant, int name){/*Do nothing*/};
 		void    InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
-		void    InputUpdateFromConstant(bool constant, int name){_error2_("Not implemented yet!");}
-		void    InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void    InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
@@ -67,6 +67,6 @@
 		void  CreateKMatrix(Matrix* Kff, Matrix* Kfs);
 		void  CreatePVector(Vector* pf);
-		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
-		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  CreateJacobianMatrix(Matrix* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13101)
@@ -239,5 +239,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -271,5 +271,5 @@
 		#endif
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -379,5 +379,5 @@
 	}
 	else{
-		_error2_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
 	}
 
@@ -572,5 +572,5 @@
 	}
 	else{
-		if (dt) pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp)/dt;
+		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp)/dt;
 		else    pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp);
 	}
@@ -616,5 +616,5 @@
 /*FUNCTION Pengrid::UpdateInputs {{{*/
 void  Pengrid::UpdateInputs(IssmDouble* solution){
-	_error2_("not supported yet!");
-}
-/*}}}*/
+	_error_("not supported yet!");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h	(revision 13101)
@@ -65,5 +65,5 @@
 		void  InputUpdateFromConstant(bool constant, int name);
 		void  InputUpdateFromSolution(IssmDouble* solution);
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
@@ -72,6 +72,6 @@
 		void  CreateKMatrix(Matrix* Kff, Matrix* Kfs);
 		void  CreatePVector(Vector* pf);
-		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
-		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  CreateJacobianMatrix(Matrix* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp	(revision 13101)
@@ -172,5 +172,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -244,5 +244,5 @@
 				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
 				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				default: _error2_("not supported yet");
+				default: _error_("not supported yet");
 			}
 		case PattynApproximationEnum:
@@ -250,5 +250,5 @@
 				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
 				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				default: _error2_("not supported yet");
+				default: _error_("not supported yet");
 			}
 		case StokesApproximationEnum:
@@ -256,5 +256,5 @@
 				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
 				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				default: _error2_("not supported yet");
+				default: _error_("not supported yet");
 			}
 		case NoneApproximationEnum:
@@ -262,7 +262,7 @@
 				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
 				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				default: _error2_("not supported yet");
+				default: _error_("not supported yet");
 			}
-		default: _error2_("not supported yet");
+		default: _error_("not supported yet");
 	}
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h	(revision 13101)
@@ -44,13 +44,13 @@
 		void  InputUpdateFromVector(int* vector, int name, int type);
 		void  InputUpdateFromVector(bool* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols,int name, int type){_error2_("Not implemented yet!");}
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error2_("Not implemented yet!");}
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type){_error2_("Not implemented yet!");}
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols,int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
 		void  InputUpdateFromConstant(bool constant, int name);
-		void  InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 			/*Load virtual functions definitions: {{{*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13101)
@@ -60,9 +60,9 @@
 
 	/*Ok, retrieve all the data needed to add a penalty between the two nodes: */
-	el1=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2);
-	el2=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3); 
-
-	node1=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0); 
-	node2=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1);
+	el1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2));
+	el2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3)) ;
+
+	node1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0));
+	node2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1));
 
 	/*id: */
@@ -93,5 +93,5 @@
 	this->length=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+6);
 	this->fraction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+9);
-	this->state=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11);
+	this->state=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11));
 
 	//intialize inputs, and add as many inputs per element as requested: 
@@ -99,8 +99,8 @@
 		
 	riftfront_type=SegmentRiftfrontEnum;
-	riftfront_fill = (int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7);
+	riftfront_fill = reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7));
 	riftfront_friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
 	riftfront_fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
-	riftfront_shelf=(bool)iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1];
+	riftfront_shelf=reCast<bool,IssmDouble>(iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1]);
 
 	this->inputs->AddInput(new IntInput(TypeEnum,riftfront_type));
@@ -276,5 +276,5 @@
 
 	/*update input*/
-	_error2_("not implemented yet");
+	_error_("not implemented yet");
 	//this->inputs->AddInput(new DoubleInput(name,constant));
 
@@ -324,5 +324,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -350,5 +350,5 @@
 			break;
 		default:
-			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
@@ -397,5 +397,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 	tria1=(Tria*)elements[0];
 	tria2=(Tria*)elements[1];
@@ -410,5 +410,5 @@
 	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
 	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
-	if (h[0]!=h[1])_error2_("different thicknesses not supported for rift fronts");
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
 	thickness=h[0];
 
@@ -488,5 +488,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 	tria1=(Tria*)elements[0];
 	tria2=(Tria*)elements[1];
@@ -504,9 +504,9 @@
 	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
 	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
-	if (h[0]!=h[1])_error2_("different thicknesses not supported for rift fronts");
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
 	thickness=h[0];
 	tria1->GetInputValue(&b[0],nodes[0],BedEnum);
 	tria2->GetInputValue(&b[1],nodes[1],BedEnum);
-	if (b[0]!=b[1])_error2_("different beds not supported for rift fronts");
+	if (b[0]!=b[1])_error_("different beds not supported for rift fronts");
 	bed=b[0];
 
@@ -536,5 +536,5 @@
 	else if(fill==MelangeEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
 
-		if(!shelf) _error2_("fill type " << fill << " not supported on ice sheets yet.");
+		if(!shelf) _error_("fill type " << fill << " not supported on ice sheets yet.");
 
 		pressure_litho=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;
@@ -546,5 +546,5 @@
 	}
 	else{
-		_error2_("fill type " << fill << " not supported yet.");
+		_error_("fill type " << fill << " not supported yet.");
 	}
 
@@ -585,5 +585,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 
 	/*recover elements on both side of rift: */
@@ -679,5 +679,5 @@
 	this->inputs->GetInputValue(&converged,ConvergedEnum);
 
-	if(converged){
+	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 
@@ -706,5 +706,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 
 	/*recover elements on both side of rift: */
@@ -751,5 +751,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 
 	/*recover elements on both side of rift: */
@@ -794,5 +794,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 
 	/*recover elements on both side of rift: */
@@ -844,5 +844,5 @@
 
 	/*enum of element? */
-	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("only Tria element allowed for Riftfront load!");
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
 
 	/*recover elements on both side of rift: */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h	(revision 13101)
@@ -62,15 +62,15 @@
 		/*Update virtual functions resolution: {{{*/
 		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void    InputUpdateFromVector(int* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVector(bool* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error2_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void    InputUpdateFromConstant(IssmDouble constant, int name);
-		void    InputUpdateFromConstant(int constant, int name){_error2_("Not implemented yet!");}
+		void    InputUpdateFromConstant(int constant, int name){_error_("Not implemented yet!");}
 		void    InputUpdateFromConstant(bool constant, int name);
-		void    InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void    InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
@@ -79,6 +79,6 @@
 		void  CreateKMatrix(Matrix* Kff, Matrix* Kfs);
 		void  CreatePVector(Vector* pf);
-		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
-		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  CreateJacobianMatrix(Matrix* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp	(revision 13101)
@@ -128,4 +128,18 @@
 }
 /*}}}*/
+/*FUNCTION Matice::GetA {{{*/
+IssmDouble Matice::GetA(){
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
 /*FUNCTION Matice::GetB {{{*/
 IssmDouble Matice::GetB(){
@@ -200,5 +214,5 @@
 			/*Get input (either in element or material)*/
 			Input* input=inputs->GetInput(input_enum);
-			if(!input) _error2_("Input " << EnumToStringx(input_enum) << " not found in material");
+			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: */
@@ -206,5 +220,5 @@
 			break;
 
-		default: _error2_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
 	}
 }
@@ -258,5 +272,5 @@
 			if(A==0){
 				/*Maxiviscositym viscosity for 0 shear areas: */
-				viscosity=2.5*pow((IssmDouble)10,(IssmDouble)17);
+				viscosity=2.5*pow(10.,17.);
 			}
 			else{
@@ -268,5 +282,5 @@
 
 	/*Checks in debugging mode*/
-	if(viscosity<=0) _error2_("Negative viscosity");
+	if(viscosity<=0) _error_("Negative viscosity");
 	_assert_(B>0);
 	_assert_(n>0);
@@ -339,5 +353,5 @@
 
 	/*Checks in debugging mode*/
-	if(viscosity3d<=0) _error2_("Negative viscosity");
+	if(viscosity3d<=0) _error_("Negative viscosity");
 	_assert_(B>0);
 	_assert_(n>0);
@@ -411,5 +425,5 @@
 
 	/*Checks in debugging mode*/
-	if(viscosity3d<=0) _error2_("Negative viscosity");
+	if(viscosity3d<=0) _error_("Negative viscosity");
 	_assert_(B>0);
 	_assert_(n>0);
@@ -628,7 +642,7 @@
 					return;
 				}
-				default: _error2_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
-			}
-		default: _error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 }
@@ -686,7 +700,7 @@
 					return;
 				}
-				default: _error2_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
-			}
-		default: _error2_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
 
@@ -775,11 +789,11 @@
 		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
 			for(i=0;i<num_control_type;i++){
-				switch((int)iomodel->Data(InversionControlParametersEnum)[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)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
 							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
@@ -813,5 +827,5 @@
 		/*Get B*/
 		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
 			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
 		}
@@ -833,11 +847,11 @@
 		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
 			for(i=0;i<num_control_type;i++){
-				switch((int)iomodel->Data(InversionControlParametersEnum)[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)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
 							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
@@ -859,5 +873,5 @@
 	#endif
 	else{
-		_error2_("Mesh type not supported yet!");
+		_error_("Mesh type not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h	(revision 13101)
@@ -66,4 +66,5 @@
 		void   GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		void   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
 		IssmDouble GetB();
 		IssmDouble GetBbar();
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h	(revision 13101)
@@ -62,8 +62,8 @@
 		void   InputUpdateFromConstant(bool constant, int name);
 		void   InputUpdateFromSolution(IssmDouble* solution);
-		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("not implemented yet");};
+		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		/*}}}*/
 		/*Material virtual functions resolution: {{{*/
-		void   InputDuplicate(int original_enum,int new_enum){_error2_("not implemented yet");};
+		void   InputDuplicate(int original_enum,int new_enum){_error_("not implemented yet");};
 		void   Configure(Elements* elements);
 		void   GetVectorFromInputs(Vector* vector,int input_enum){return;}
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp	(revision 13101)
@@ -70,5 +70,5 @@
 
 	/*spc all nodes on water*/
-	if (!iomodel->Data(MaskVertexonwaterEnum)) _error2_("iomodel->nodeonwater is NULL");
+	if (!iomodel->Data(MaskVertexonwaterEnum)) _error_("iomodel->nodeonwater is NULL");
 	if (reCast<IssmBool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
 		for(k=1;k<=gsize;k++){
@@ -89,14 +89,17 @@
 			_assert_(iomodel->Data(MeshVertexonbedEnum)); 
 			_assert_(iomodel->Data(FlowequationVertexEquationEnum));
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealApproximationEnum && !iomodel->Data(MeshVertexonbedEnum)[io_index]){
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 				for(k=1;k<=gsize;k++) this->FreezeDof(k);
 			}
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
-				if(!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==L1L2ApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+				for(k=1;k<=gsize;k++) this->FreezeDof(k);
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 					for(k=1;k<=gsize;k++) this->FreezeDof(k);
 				}
 			}
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
-				if(!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 					for(k=1;k<=2;k++) this->FreezeDof(k);
 				}
@@ -114,5 +117,5 @@
 	/*Diagnostic Hutter*/
 	if (analysis_type==DiagnosticHutterAnalysisEnum){
-		if (!iomodel->Data(FlowequationVertexEquationEnum)) _error2_("iomodel->vertices_type is NULL");
+		_assert_(iomodel->Data(FlowequationVertexEquationEnum));
 		/*Constrain all nodes that are not Hutter*/
 		if (reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])!=HutterApproximationEnum){
@@ -230,5 +233,5 @@
 		return indexing.sdoflist[dofindex];
 	}
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 
 }
@@ -302,5 +305,5 @@
 			else for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
 		}
-		else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 	}
 }
@@ -342,5 +345,5 @@
 			}
 		}
-		else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 	}
 	else{
@@ -411,5 +414,5 @@
 			}
 		}
-		else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 	}
 }
@@ -597,5 +600,5 @@
 		else if (setenum==FsetEnum) numdofs=this->indexing.fsize;
 		else if (setenum==SsetEnum) numdofs=this->indexing.ssize;
-		else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 	}
 	else{
@@ -627,5 +630,5 @@
 			else numdofs=this->indexing.ssize;
 		}
-		else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 	}
 	return numdofs;
@@ -834,5 +837,5 @@
 		}
 	}
-	else _error2_("VecMerge can only merge from the s or f-set onto the g-set!");
+	else _error_("VecMerge can only merge from the s or f-set onto the g-set!");
 
 	/*Free ressources:*/
@@ -880,5 +883,5 @@
 		}
 	}
-	else _error2_("VecReduce can only merge from the s or f-set onto the g-set!");
+	else _error_("VecReduce can only merge from the s or f-set onto the g-set!");
 
 	/*Free ressources:*/
@@ -927,5 +930,5 @@
 		dofcount+=this->indexing.ssize;
 	}
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 
 
@@ -956,5 +959,5 @@
 		for(i=0;i<this->indexing.ssize;i++) indexing.sdoflist[i]+=dofcount;
 	}
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 }
 /*}}}*/
@@ -972,5 +975,5 @@
 	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++)  *(truedofs+ncols*sid+j)=indexing.fdoflist[j];
 	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++)  *(truedofs+ncols*sid+j)=indexing.sdoflist[j];
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 
 }
@@ -991,5 +994,5 @@
 	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=*(alltruedofs+ncols*sid+j);
 	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=*(alltruedofs+ncols*sid+j);
-	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h	(revision 13101)
@@ -45,5 +45,5 @@
 		int   MyRank();
 		int   ObjectEnum();
-		Object* copy(){_error2_("Not implemented yet (similar to Elements)");};
+		Object* copy(){_error_("Not implemented yet (similar to Elements)");};
 		/*}}}*/
 		/*Update virtual functions definitions: {{{*/
@@ -59,6 +59,6 @@
 		void  InputUpdateFromConstant(int constant, int name);
 		void  InputUpdateFromConstant(bool constant, int name);
-		void  InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("Not implemented yet!");}
+		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("Not implemented yet!");}
 		/*}}}*/
 		/*Node numerical routines {{{*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h	(revision 13101)
@@ -31,8 +31,8 @@
 		virtual void  DeepEcho();
 		virtual void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h	(revision 13101)
@@ -28,8 +28,8 @@
 		void  DeepEcho();
 		void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionCellEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
@@ -39,12 +39,12 @@
 		int   NDims();
 		int*  Size();
-		void  Get(int* pvalue){_error2_("An OptionCell object cannot return a int");};
-		void  Get(IssmDouble* pvalue){_error2_("An OptionCell object cannot return a IssmDouble");};
-		void  Get(bool* pvalue){  _error2_("An OptionCell object cannot return a bool");};
-		void  Get(char** pvalue){ _error2_("An OptionCell object cannot return a string");};
-		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionCell object cannot return a string vec");};
-		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionCell object cannot return a IssmDouble vec");};
+		void  Get(int* pvalue){_error_("An OptionCell object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error_("An OptionCell object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error_("An OptionCell object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionCell object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionCell object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error_("An OptionCell object cannot return a IssmDouble vec");};
 		void  Get(Options** pvalue);
-		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionCell object cannot return an Options DataSet vec");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionCell object cannot return an Options DataSet vec");};
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp	(revision 13101)
@@ -153,5 +153,5 @@
 	/*We should first check that the size is at least one*/
 	if(this->NumEl()<=0){
-		_error2_("option \"" << this->name << "\" is empty and cannot return a string vector");
+		_error_("option \"" << this->name << "\" is empty and cannot return a string vector");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h	(revision 13101)
@@ -28,8 +28,8 @@
 		void  DeepEcho();
 		void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionCharEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
@@ -39,12 +39,12 @@
 		int   NDims();
 		int*  Size();
-		void  Get(int* pvalue){_error2_("An OptionChar object cannot return a int");};
-		void  Get(IssmDouble* pvalue){_error2_("An OptionChar object cannot return a IssmDouble");};
-		void  Get(bool* pvalue){  _error2_("An OptionChar object cannot return a bool");};
+		void  Get(int* pvalue){_error_("An OptionChar object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error_("An OptionChar object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error_("An OptionChar object cannot return a bool");};
 		void  Get(char** pvalue);
 		void  Get(char*** ppvalue,int *pnumel);
-		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionChar object cannot return a IssmDouble vec");};
-		void  Get(Options** pvalue){ _error2_("An OptionChar object cannot return an Options DataSet");};
-		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionChar object cannot return an Options DataSet vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error_("An OptionChar object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue){ _error_("An OptionChar object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionChar object cannot return an Options DataSet vec");};
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp	(revision 13101)
@@ -125,5 +125,5 @@
 	/*We should first check that the size is one*/
 	if(this->NumEl()!=1){
-		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single int");
+		_error_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single int");
 	}
 
@@ -137,5 +137,5 @@
 	/*We should first check that the size is one*/
 	if(this->NumEl()!=1){
-		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single IssmDouble");
+		_error_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single IssmDouble");
 	}
 
@@ -149,5 +149,5 @@
 	/*We should first check that the size is at least one*/
 	if(this->NumEl()<=0){
-		_error2_("option \"" << this->name << "\" is empty and cannot return a IssmDouble vector");
+		_error_("option \"" << this->name << "\" is empty and cannot return a IssmDouble vector");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h	(revision 13101)
@@ -28,8 +28,8 @@
 		void  DeepEcho();
 		void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionDoubleEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
@@ -41,10 +41,10 @@
 		void  Get(int* pvalue);
 		void  Get(IssmDouble* pvalue);
-		void  Get(bool* pvalue){  _error2_("An OptionDouble object cannot return a bool");};
-		void  Get(char** pvalue){ _error2_("An OptionDouble object cannot return a string");};
-		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionDouble object cannot return a string vec");};
+		void  Get(bool* pvalue){  _error_("An OptionDouble object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionDouble object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionDouble object cannot return a string vec");};
 		void  Get(IssmDouble** pvalue,int* pnumel);
-		void  Get(Options** pvalue){ _error2_("An OptionDouble object cannot return an Options DataSet");};
-		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionDouble object cannot return an Options DataSet vec");};
+		void  Get(Options** pvalue){ _error_("An OptionDouble object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionDouble object cannot return an Options DataSet vec");};
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp	(revision 13101)
@@ -125,5 +125,5 @@
 	/*We should first check that the size is one*/
 	if(this->NumEl()!=1){
-		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single bool");
+		_error_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single bool");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h	(revision 13101)
@@ -28,8 +28,8 @@
 		void  DeepEcho();
 		void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionLogicalEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
@@ -39,12 +39,12 @@
 		int   NDims();
 		int*  Size();
-		void  Get(int* pvalue){_error2_("An OptionLogical object cannot return a int");};
-		void  Get(IssmDouble* pvalue){_error2_("An OptionLogical object cannot return a IssmDouble");};
+		void  Get(int* pvalue){_error_("An OptionLogical object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error_("An OptionLogical object cannot return a IssmDouble");};
 		void  Get(bool* pvalue);
-		void  Get(char** pvalue){ _error2_("An OptionLogical object cannot return a string");};
-		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionLogical object cannot return a string vec");};
-		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionLogical object cannot return a IssmDouble vec");};
-		void  Get(Options** pvalue){ _error2_("An OptionLogical object cannot return an Options DataSet");};
-		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionLogical object cannot return an Options DataSet vec");};
+		void  Get(char** pvalue){ _error_("An OptionLogical object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionLogical object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error_("An OptionLogical object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue){ _error_("An OptionLogical object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionLogical object cannot return an Options DataSet vec");};
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp	(revision 13101)
@@ -132,5 +132,5 @@
 	/*We should first check that the size is one*/
 	if(this->NumEl()!=1){
-		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single options dataset");
+		_error_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single options dataset");
 	}
 
@@ -144,5 +144,5 @@
 	/*We should first check that the size is at least one*/
 	if(this->NumEl()<=0){
-		_error2_("option \"" << this->name << "\" is empty and cannot return an options dataset vector");
+		_error_("option \"" << this->name << "\" is empty and cannot return an options dataset vector");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h	(revision 13101)
@@ -28,8 +28,8 @@
 		void  DeepEcho();
 		void  DeepEcho(char* indent);
-		int   Id(){_error2_("Not implemented yet");};
-		int   MyRank(){_error2_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
 		int   ObjectEnum(){return OptionStructEnum;};
-		Object* copy(){_error2_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
 		/*}}}*/
 
@@ -39,10 +39,10 @@
 		int   NDims();
 		int*  Size();
-		void  Get(int* pvalue){_error2_("An OptionStruct object cannot return a int");};
-		void  Get(IssmDouble* pvalue){_error2_("An OptionStruct object cannot return a IssmDouble");};
-		void  Get(bool* pvalue){  _error2_("An OptionStruct object cannot return a bool");};
-		void  Get(char** pvalue){ _error2_("An OptionStruct object cannot return a string");};
-		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionStruct object cannot return a string vec");};
-		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionStruct object cannot return a IssmDouble vec");};
+		void  Get(int* pvalue){_error_("An OptionStruct object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error_("An OptionStruct object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error_("An OptionStruct object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionStruct object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionStruct object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error_("An OptionStruct object cannot return a IssmDouble vec");};
 		void  Get(Options** pvalue);
 		void  Get(Options*** ppvalue,int *pnumel);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 13101)
@@ -27,5 +27,5 @@
 	/*check for index too large  */
 	for (i=0;i<ndims;i++) aprod*=size[i];
-	if (index >= aprod) _error2_("Index " << index << " exceeds number of elements " << aprod << ".");
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
 
 	/*calculate the dimensions (being careful of integer division)  */
@@ -46,5 +46,5 @@
 	/*check for any dimension too large  */
 	for (i=0;i<ndims;i++){
-		if (dims[i] >= size[i]) _error2_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
 	}
 
@@ -65,5 +65,5 @@
 	/*check for index too large  */
 	for (i=0; i<ndims; i++) aprod*=size[i];
-	if (index >= aprod) _error2_("Index " << index << " exceeds number of elements " << aprod << ".");
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
 
 	/*calculate the dimensions (being careful of integer division)  */
@@ -84,5 +84,5 @@
 	/*check for any dimension too large  */
 	for (i=0; i<ndims; i++){
-		if (dims[i] >= size[i]) _error2_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h	(revision 13101)
@@ -43,31 +43,31 @@
 		int   InstanceEnum(){return enum_type;}
 		void  GetParameterValue(bool* pbool){*pbool=value;}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << ") cannot return a FILE");}
 
 		void  SetValue(bool boolean){this->value=boolean;}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an int");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an IssmPDouble");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold an int");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold an IssmPDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 		
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13101)
@@ -45,31 +45,31 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
 		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims);
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
-		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array);
 		void  UnitConversion(int direction_enum);
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13101)
@@ -109,5 +109,5 @@
 /*FUNCTION DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
 void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
-	_error2_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+	_error_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13101)
@@ -44,32 +44,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
 		void  GetParameterValue(int** pintarray,int* pM,int* pN);
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN);
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
 		void  SetValue(IssmDouble* IssmDoublearray,int M,int N);
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
-		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13101)
@@ -82,30 +82,30 @@
 /*FUNCTION DoubleParam::GetParameterValue(int* pinteger){{{*/
 void DoubleParam::GetParameterValue(int* pinteger){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
 }
 /*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{*/
 void DoubleParam::GetParameterValue(bool* pbool){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
 }
 /*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM){{{*/
 void DoubleParam::GetParameterValue(int** pintarray,int* pM){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
 }
 /*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
 void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
 }
 /*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
 void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
 }
 /*}}}*/
 /*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
 void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
-	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h	(revision 13101)
@@ -48,27 +48,27 @@
 		void  GetParameterValue(int** pintarray,int* pM,int* pN);
 		void  GetParameterValue(IssmDouble* pIssmDouble){*pIssmDouble=value;}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
 		void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
 		void  SetValue(int integer){this->value=(IssmDouble)integer;}
 		void  SetValue(IssmDouble scalar){this->value=(IssmDouble)scalar;}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13101)
@@ -124,5 +124,5 @@
 /*FUNCTION DoubleVecParam::GetParameterValue(int** pintarray,int* pM){{{*/
 void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){
-	_error2_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+	_error_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
 }
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13101)
@@ -43,32 +43,32 @@
 		/*Param virtual functions definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
 		void  GetParameterValue(int** pintarray,int* pM);
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
 		void  SetValue(IssmDouble* IssmDoublearray,int M);
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 		
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h	(revision 13101)
@@ -42,32 +42,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){  _error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(bool* pbool){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){*pfid=value;};
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("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){_error2_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h	(revision 13101)
@@ -44,32 +44,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
 		void  GetParameterValue(int** pintarray,int* pM,int* pN);
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
 		void  SetValue(int* intarray,int M,int N);
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h	(revision 13101)
@@ -43,32 +43,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
 		void  GetParameterValue(int* pinteger){*pinteger=value;}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
 		void  SetValue(int integer){this->value=integer;}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
-		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h	(revision 13101)
@@ -44,32 +44,32 @@
 		/*Param virtual functions definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
 		void  GetParameterValue(int** pintarray,int* pM);
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
 		void  SetValue(int* intarray,int M);
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 		
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h	(revision 13101)
@@ -43,32 +43,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
 		void  GetParameterValue(Matrix** poutput);
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
 		void  SetValue(Matrix* mat);
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h	(revision 13101)
@@ -45,32 +45,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
 		void  GetParameterValue(char*** pstringarray,int* pM);
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
 		void  SetValue(char** stringarray,int M);
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h	(revision 13101)
@@ -43,32 +43,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
 		void  GetParameterValue(char** pstring);
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
 		void  SetValue(char* string);
-		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
-		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp	(revision 13101)
@@ -99,5 +99,5 @@
 void  TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){
 
-	double output;
+	IssmDouble output;
 	bool   found;
 
@@ -136,5 +136,5 @@
 		}
 	}
-	if(!found)_error2_("did not find time interval on which to interpolate values");
+	if(!found)_error_("did not find time interval on which to interpolate values");
 	*pdouble=output;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h	(revision 13101)
@@ -44,32 +44,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(bool* pbool){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
 		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time);
-		void  GetParameterValue(char** pstring){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Vector** pvec){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
-		void  GetParameterValue(FILE** pfid){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(char** pstring){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
-		void  SetValue(int* intarray,int M,int N){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
-		void  SetValue(Vector* vec){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
-		void  SetValue(Matrix* mat){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector* vec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h	(revision 13101)
@@ -43,32 +43,32 @@
 		/*Param vritual function definitions: {{{*/
 		int   InstanceEnum(){return enum_type;}
-		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
-		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
-		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
-		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
-		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
-		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
-		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Matrix** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(Vector** poutput);
-		void  GetParameterValue(FILE** pfid){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
 
-		void  SetValue(bool boolean){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
-		void  SetValue(int integer){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
-		void  SetValue(IssmDouble scalar){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
-		void  SetValue(char* string){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
-		void  SetValue(char** stringarray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
-		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
-		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
-		void  SetValue(int* intarray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
-		void  SetValue(int* pintarray,int M,int N){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
 		void  SetValue(Vector* vec);
-		void  SetValue(Matrix* mat){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
-		void  SetValue(FILE* fid){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
-		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  SetValue(Matrix* mat){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
 		void  UnitConversion(int direction_enum);
 
Index: /issm/branches/trunk-jpl-damage/src/c/include/macros.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/include/macros.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/include/macros.h	(revision 13101)
@@ -23,23 +23,13 @@
 #define _printf_(flag,...) do{if(flag) PrintfFunction(__VA_ARGS__);}while(0)
 /*}}}*/
-/* _error_ {{{*/
-/*Error exception macro*/
-#ifdef _INTEL_WIN_
-#define _error_(...)\
-  throw ErrorException(exprintf(__VA_ARGS__))
-#else
-#define _error_(...)\
-  throw ErrorException(__FILE__,__func__,__LINE__,exprintf(__VA_ARGS__))
-#endif
-/*}}}*/
 /* _error2_ {{{*/
 /*new Error exception macro*/
 #ifdef _INTEL_WIN_
-#define _error2_(StreamArgs)\
+#define _error_(StreamArgs)\
    do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
    aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
    throw ErrorException(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
 #else
-#define _error2_(StreamArgs)\
+#define _error_(StreamArgs)\
 	do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
    aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
@@ -75,5 +65,5 @@
 #ifdef _ISSM_DEBUG_ 
 #define _assert_(statement)\
-  if (!(statement)) _error_("Assertion \"%s\" failed, please report bug to %s",#statement,PACKAGE_BUGREPORT)
+  if (!(statement)) _error_("Assertion \""<<#statement<<"\" failed, please report bug to "<<PACKAGE_BUGREPORT)
 #else
 #define _assert_(ignore)\
Index: /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 13101)
@@ -18,4 +18,4 @@
 	extern int my_rank;
 	_assert_(fid);
-	if(fclose(fid)!=0)_error2_("could not close file " << filename);
+	if(fclose(fid)!=0)_error_("could not close file " << filename);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 13101)
@@ -20,5 +20,5 @@
 	/*Open handle to data on disk: */
 	fid=fopen(filename,format);
-	if(fid==NULL) _error2_("could not open file " << filename << " for binary reading or writing"); 
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing"); 
 
 	return fid;
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 13101)
@@ -22,9 +22,9 @@
 		/* special case: */
 		function();
-		_error2_("usage: see above");
+		_error_("usage: see above");
 	}
 	else if (nlhs!=NLHS || nrhs!=NRHS ) {
 		function(); 
-		_error2_("usage error.");
+		_error_("usage error.");
 	}
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp	(revision 13101)
@@ -48,5 +48,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -89,5 +89,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -134,5 +134,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -176,5 +176,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -238,5 +238,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -269,5 +269,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -301,5 +301,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -333,5 +333,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -365,5 +365,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -381,5 +381,5 @@
 	/*Ok, the string should be coming directly from the matlab workspace: */
 	if (!mxIsClass(dataref,"char")){
-		_error2_("input data_type is not a string!");
+		_error_("input data_type is not a string!");
 	}
 	else{
@@ -416,5 +416,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -434,5 +434,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error2_("input data_type is not a double!");
+		_error_("input data_type is not a double!");
 	}
 	else{
@@ -451,5 +451,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error2_("input data_type is not a scalar!");
+		_error_("input data_type is not a scalar!");
 	}
 	else{
@@ -468,10 +468,10 @@
 
 	if (mxIsClass(dataref,"logical")){
-		if(mxGetM(dataref)!=1) _error2_("input data is not of size 1x1");
-		if(mxGetN(dataref)!=1) _error2_("input data is not of size 1x1");
+		if(mxGetM(dataref)!=1) _error_("input data is not of size 1x1");
+		if(mxGetN(dataref)!=1) _error_("input data is not of size 1x1");
 		mxbool_ptr=mxGetLogicals(dataref);
 	}
 	else{
-		_error2_("input data_type is not a bool!");
+		_error_("input data_type is not a bool!");
 	}
 
@@ -495,5 +495,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -519,5 +519,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -620,8 +620,8 @@
 	/*Fetch all options*/
 	for (int i=istart; i<nrhs; i=i+2){
-		if (!mxIsClass(pdataref[i],"char")) _error2_("Argument " << i+1 << " must be name of option");
+		if (!mxIsClass(pdataref[i],"char")) _error_("Argument " << i+1 << " must be name of option");
 
 		FetchData(&name,pdataref[i]);
-		if(i+1 == nrhs) _error2_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
+		if(i+1 == nrhs) _error_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
 
 		option=(Option*)OptionParse(name,&pdataref[i+1]);
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13101)
@@ -119,5 +119,5 @@
 	}
 	else{
-		_error2_("Matlab matrix type Not implemented yet");
+		_error_("Matlab matrix type Not implemented yet");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13101)
@@ -46,5 +46,5 @@
 		
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		nz=(int)((double)nnz/(double)rows);
@@ -77,5 +77,5 @@
 
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		/*allocate and memcpy*/
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp	(revision 13101)
@@ -27,5 +27,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"double")){
-		_error2_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 	FetchData(&odouble->values,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
@@ -45,5 +45,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"logical")){
-		_error2_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 	FetchData(&ological->values,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
@@ -63,5 +63,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"char")){
-		_error2_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 	FetchData(&ochar->values,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
@@ -87,5 +87,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"struct")){
-		_error2_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 	ostruct->numel=mxGetNumberOfElements(prhs[0]);
@@ -133,5 +133,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"cell")){
-		_error2_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 
@@ -181,5 +181,5 @@
 			mxDestroyArray(lhs[0]);
 		}
-		else _error2_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13101)
@@ -9,11 +9,11 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* norm_list,int step){
+void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* norm_list,int step){
 
 	/*Intermediaries*/
 	int     i,j,num_controls;
 	int    *control_type = NULL;
-	double *scalar_list = NULL;
-	double  scalar;
+	IssmDouble *scalar_list = NULL;
+	IssmDouble  scalar;
 
 
@@ -38,4 +38,4 @@
 	/*Clean up and return*/
 	xDelete<int>(control_type);
-	xDelete<double>(scalar_list);
+	xDelete<IssmDouble>(scalar_list);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 13101)
@@ -8,5 +8,5 @@
 #include "../../Container/Container.h"
 
-void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* norm_list,int step);
+void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* norm_list,int step);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 13101)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* gradient){
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* gradient){
 
 	/*Intermediaries*/
@@ -33,5 +33,5 @@
 
 	/*Serialize gradient*/
-	double* serial_gradient=NULL;
+	IssmDouble* serial_gradient=NULL;
 	serial_gradient=gradient->ToMPISerial();
 
@@ -39,4 +39,4 @@
 
 	/*Clean up and return*/
-	xDelete<double>(serial_gradient);
+	xDelete<IssmDouble>(serial_gradient);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 13101)
@@ -11,15 +11,14 @@
 #include "../Responsex/Responsex.h"
 
-void CostFunctionx(double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+void CostFunctionx(IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
 	int      i;
 	int      num_responses;
-	double   S;
 	Element *element       = NULL;
 	int     *responses     = NULL;
 
 	/*output: */
-	double J,Jplus;
+	IssmDouble J,Jplus;
 	
 	/*Recover parameters*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void CostFunctionx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+void CostFunctionx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 13101)
@@ -86,5 +86,5 @@
 		}
 		else if (flag==NodalEnum){
-			_error2_("nodal response functions not supported yet!");
+			_error_("nodal response functions not supported yet!");
 
 			/*increment response_pointer :*/
@@ -104,5 +104,5 @@
 			}
 		}
-		else _error2_("flag type " << flag << " not supported yet for response analysis");
+		else _error_("flag type " << flag << " not supported yet for response analysis");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 13101)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
+	if(!pch)_error_("descriptor " << descriptor << " is not correctly formatted!");
 
 	if (strncmp(pch,"scaled",6)==0){
 		/*we have a scaled variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("scaled descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 
@@ -44,9 +44,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return IndexedEnum;
@@ -55,9 +55,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 13101)
@@ -72,5 +72,5 @@
 	if(control_analysis)solutioncore=&control_core;
 	#else
-	_error2_("ISSM was not compiled with control capabilities, exiting!");
+	_error_("ISSM was not compiled with control capabilities, exiting!");
 	#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
+void ElementResponsex( IssmDouble* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
 	
 
@@ -20,5 +20,5 @@
 	int cpu_found=-1;
 	int index;
-	double response;
+	IssmDouble response;
 	Element* element=NULL;
 
@@ -39,5 +39,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error2_("could not find material with id" << index << " to compute ElementResponse");
+	if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
 	#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int response_enum,bool process_units);
+void ElementResponsex( IssmDouble* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int response_enum,bool process_units);
 
 #endif  /* _ELEMENTRESPONSEX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13101)
@@ -17,7 +17,5 @@
 	switch(en){
 
-		case AutodiffForwardEnum : return "AutodiffForward";
 		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
-		case AutodiffReverseEnum : return "AutodiffReverse";
 		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
 		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
@@ -55,4 +53,5 @@
 		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
 		case FlowequationIshutterEnum : return "FlowequationIshutter";
+		case FlowequationIsl1l2Enum : return "FlowequationIsl1l2";
 		case FlowequationIsmacayealpattynEnum : return "FlowequationIsmacayealpattyn";
 		case FlowequationIsstokesEnum : return "FlowequationIsstokes";
@@ -239,9 +238,10 @@
 		case TransientSolutionEnum : return "TransientSolution";
 		case ApproximationEnum : return "Approximation";
+		case NoneApproximationEnum : return "NoneApproximation";
 		case HutterApproximationEnum : return "HutterApproximation";
 		case MacAyealApproximationEnum : return "MacAyealApproximation";
 		case MacAyealPattynApproximationEnum : return "MacAyealPattynApproximation";
 		case MacAyealStokesApproximationEnum : return "MacAyealStokesApproximation";
-		case NoneApproximationEnum : return "NoneApproximation";
+		case L1L2ApproximationEnum : return "L1L2Approximation";
 		case PattynApproximationEnum : return "PattynApproximation";
 		case PattynStokesApproximationEnum : return "PattynStokesApproximation";
@@ -283,4 +283,5 @@
 		case NumericalfluxEnum : return "Numericalflux";
 		case ParamEnum : return "Param";
+		case L1L2IceFrontEnum : return "L1L2IceFront";
 		case PattynIceFrontEnum : return "PattynIceFront";
 		case PengridEnum : return "Pengrid";
@@ -376,4 +377,6 @@
 		case EnthalpyPicardEnum : return "EnthalpyPicard";
 		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
+		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
 		case StepResponsesEnum : return "StepResponses";
 		case IntMatParamEnum : return "IntMatParam";
@@ -396,8 +399,4 @@
 		case StressTensoryzEnum : return "StressTensoryz";
 		case StressTensorzzEnum : return "StressTensorzz";
-		case IceVolumeEnum : return "IceVolume";
-		case TotalSmbEnum : return "TotalSmb";
-		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
-		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
 		case P0Enum : return "P0";
 		case P1Enum : return "P1";
@@ -433,4 +432,6 @@
 		case MaxVzEnum : return "MaxVz";
 		case MaxAbsVzEnum : return "MaxAbsVz";
+		case IceVolumeEnum : return "IceVolume";
+		case TotalSmbEnum : return "TotalSmb";
 		case RelativeEnum : return "Relative";
 		case AbsoluteEnum : return "Absolute";
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13101)
@@ -55,5 +55,5 @@
 
 	if (!DomainOutlineRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
-		_error2_("Error reading exp file.");
+		_error_("Error reading exp file.");
 	_pprintLine_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".");
 //	for (i=0; i<nprof; i++)
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13101)
@@ -26,5 +26,5 @@
 	/*Get size of vector: */
 	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
-	if (gsize==0) _error2_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
+	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
 	
 	/*Initialize solution: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13101)
@@ -36,8 +36,8 @@
 }
 
-void GetVectorFromControlInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
+void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
 	
 	/*output: */
-	double* vector=NULL;
+	IssmDouble* vector=NULL;
 	
 	/*intermediary: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13101)
@@ -10,5 +10,5 @@
 /* local prototypes: */
 void	GetVectorFromControlInputsx( Vector** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
-void	GetVectorFromControlInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
 
 #endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13101)
@@ -32,5 +32,5 @@
 	}
 	else{
-		_error2_("vector type: " << EnumToStringx(type) << " not supported yet!");
+		_error_("vector type: " << EnumToStringx(type) << " not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 13101)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void Gradjx(Vector** pgradient,double** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+void Gradjx(Vector** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
 	int     i,j,numberofvertices;
 	int     num_controls;
-	double   norm_inf;
-	double  *norm_list     = NULL;
+	IssmDouble   norm_inf;
+	IssmDouble  *norm_list     = NULL;
 	int     *control_type  = NULL;
 	Vector  *gradient      = NULL;
@@ -27,5 +27,5 @@
 	/*Allocate gradient_list */
 	gradient_list = xNew<Vector*>(num_controls);
-	norm_list = xNew<double>(num_controls);
+	norm_list = xNew<IssmDouble>(num_controls);
 	for(i=0;i<num_controls;i++){
 		gradient_list[i]=new Vector(num_controls*numberofvertices);
@@ -54,6 +54,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*Clean-up and assign output pointer*/
@@ -62,5 +62,5 @@
 	}
 	else{
-		xDelete<double>(norm_list);
+		xDelete<IssmDouble>(norm_list);
 	}
 	if(pgradient)  *pgradient=gradient;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void Gradjx(Vector** pgrad_g,double** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
+void Gradjx(Vector** pgrad_g,IssmDouble** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
 
 #endif  /* _GRADJX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13101)
@@ -14,7 +14,7 @@
 
 	int      i, migration_style,analysis_type;
-	double*  vertices_potentially_ungrounding = NULL;
-	double*  vertices_ungrounding             = NULL;
-	double*  old_floatingice                  = NULL;
+	IssmDouble*  vertices_potentially_ungrounding = NULL;
+	IssmDouble*  vertices_ungrounding             = NULL;
+	IssmDouble*  old_floatingice                  = NULL;
 	Vector*      vec_old_floatingice              = NULL;
 	Element* element                          = NULL;
@@ -27,5 +27,5 @@
 
 	if(migration_style==NoneEnum) return;
-	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error2_(EnumToStringx(migration_style) << " not supported yet!");
+	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error_(EnumToStringx(migration_style) << " not supported yet!");
 
 	if(migration_style==SoftMigrationEnum){
@@ -49,7 +49,7 @@
 	/*free ressouces: */
 	xdelete(&vec_old_floatingice);
-	xDelete<double>(vertices_potentially_ungrounding);
-	xDelete<double>(vertices_ungrounding);
-	xDelete<double>(old_floatingice);
+	xDelete<IssmDouble>(vertices_potentially_ungrounding);
+	xDelete<IssmDouble>(vertices_ungrounding);
+	xDelete<IssmDouble>(old_floatingice);
 }
 
@@ -82,8 +82,8 @@
 /*%}}}*/
 /*FUNCTION PotentialSheetUngrounding {{{*/
-double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
+IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
 
 	int      i,numberofvertices;
-	double*  vertices_potentially_ungrounding      = NULL;
+	IssmDouble*  vertices_potentially_ungrounding      = NULL;
 	Vector*      vec_vertices_potentially_ungrounding  = NULL;
 	Element* element                               = NULL;
@@ -109,11 +109,11 @@
 /*}}}*/
 /*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
-double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding){ 
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ 
 
 	int      i,analysis_type;
 	int      numberofvertices;
 	int      nflipped,local_nflipped;
-	double*  nodes_on_floatingice                  = NULL;
-	double*  elements_neighboring_floatingce      = NULL;
+	IssmDouble*  nodes_on_floatingice                  = NULL;
+	IssmDouble*  elements_neighboring_floatingce      = NULL;
 	Vector*      vec_elements_neighboring_floatingice = NULL;
 	Vector*      vec_nodes_on_floatingice              = NULL;
@@ -150,5 +150,5 @@
 		for(i=0;i<elements->Size();i++){
 			element=(Element*)elements->GetObjectByOffset(i);
-			if(elements_neighboring_floatingce[element->Sid()]){
+			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
 				local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
 			}
@@ -164,6 +164,6 @@
 
 		/*Avoid leaks: */
-		xDelete<double>(elements_neighboring_floatingce);
-		xDelete<double>(nodes_on_floatingice);
+		xDelete<IssmDouble>(elements_neighboring_floatingce);
+		xDelete<IssmDouble>(nodes_on_floatingice);
 
 		/*Assemble and serialize:*/
@@ -174,5 +174,5 @@
 	/*Free ressources:*/
 	xdelete(&vec_nodes_on_floatingice);
-	xDelete<double>(elements_neighboring_floatingce);
+	xDelete<IssmDouble>(elements_neighboring_floatingce);
 
 	return nodes_on_floatingice;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 13101)
@@ -15,5 +15,5 @@
 
 Vector*        CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
-double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
-double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding);
+IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding);
 #endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 13101)
@@ -10,8 +10,8 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void IceVolumex(IssmDouble* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 
-	double local_ice_volume = 0;
-	double total_ice_volume;
+	IssmDouble local_ice_volume = 0;
+	IssmDouble total_ice_volume;
 
 	for(int i=0;i<elements->Size();i++){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void IceVolumex(IssmDouble* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13101)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,double scalar,bool save_parameter){
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,IssmDouble scalar,bool save_parameter){
 
 	/*Go through elemnets, and ask to carry out the operation on inputs: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 13101)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, double scalar,bool save_parameter);
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, IssmDouble scalar,bool save_parameter);
 
 #endif 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13101)
@@ -95,8 +95,8 @@
 		}
 		else if (strncmp(descriptor,"indexed_",8)==0){
-			_error2_("indexed variables not supported yet!");
+			_error_("indexed variables not supported yet!");
 		}
 		else if (strncmp(descriptor,"nodal_",8)==0){
-			_error2_("nodal variables not supported yet!");
+			_error_("nodal variables not supported yet!");
 		}
 		else{
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13101)
@@ -37,11 +37,11 @@
 	/*Some checks on arguments: */
 	if ((M<2) || (N<2) || (nods<=0)){
-		_error2_("nothing to be done according to the dimensions of input matrices and vectors.");
+		_error_("nothing to be done according to the dimensions of input matrices and vectors.");
 	}
 	if (x_in[1]-x_in[0]<0){
-		_error2_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
+		_error_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
 	}
 	if (y_in[1]-y_in[0]<0){
-		_error2_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
+		_error_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
 	}
 
@@ -69,5 +69,5 @@
 	}
 	else{
-		_error2_("x and y vectors length should be 1 or 0 more than data number of rows.");
+		_error_("x and y vectors length should be 1 or 0 more than data number of rows.");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13101)
@@ -40,5 +40,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<3 || nods_prime==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -54,9 +54,9 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
 	if((numcontours) && (interpolation_type==2)){
-		_error2_("element interpolation_type with contours not supported yet!");
+		_error_("element interpolation_type with contours not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 	/*some checks*/
 	if (nels<1 || nods<3 || nlines<1 || ncols<1 || xposting==0 || yposting==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,5 +41,5 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13101)
@@ -35,5 +35,5 @@
 	/*Checks*/
 	if (M_data!=nods_data && M_data!=nels_data){
-		_error2_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
+		_error_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
 	}
 
@@ -138,5 +138,5 @@
 			for (j=0;j<N_data;j++){
 				if (it<0 || it>=nels_data){
-					_error2_("Triangle number " << it << " not in [0 " << nels_data << "], report bug to developers");
+					_error_("Triangle number " << it << " not in [0 " << nels_data << "], report bug to developers");
 				}
 				data_interp[i*N_data+j]=data[N_data*it+j];
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 13101)
@@ -27,5 +27,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<6 || nods_prime==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,5 +41,5 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13101)
@@ -38,6 +38,6 @@
 	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
 
-	if(code!=7)_error2_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
-	if(vector_layout!=1)_error2_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
 
 	/*Fetch vector:*/
@@ -99,5 +99,5 @@
 	}
 	else{
-		_error2_("Size of field " << EnumToStringx(vector_enum) << " not supported");
+		_error_("Size of field " << EnumToStringx(vector_enum) << " not supported");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 13101)
@@ -133,5 +133,5 @@
 					}
 					else
-						_error2_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
+						_error_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
 				}
 				jpt++;
@@ -173,5 +173,5 @@
 
 		else
-			_error2_("Data matrix has incorrect number of " << mdata << " rows.\n");
+			_error_("Data matrix has incorrect number of " << mdata << " rows.\n");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13101)
@@ -44,5 +44,5 @@
 	fidi=fopen(filkml,"r");
 	if (!(kobj=KMLFileReadx(fidi)))
-		_error2_("Error reading kml file.");
+		_error_("Error reading kml file.");
 	fclose(fidi);
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp	(revision 13101)
@@ -138,5 +138,5 @@
 	}
 	else{
-		_error2_("output '" << output << "' not supported yet");
+		_error_("output '" << output << "' not supported yet");
 	}
 
@@ -305,5 +305,5 @@
 		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
 		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
-		else _error2_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
+		else _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
 	}
 	else variogram = new GaussianVariogram(options);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13101)
@@ -103,5 +103,5 @@
 	}
 	else{
-		_error2_("output '" << output << "' not supported yet");
+		_error_("output '" << output << "' not supported yet");
 	}
 
@@ -126,5 +126,5 @@
 		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
 		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
-		else _error2_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
+		else _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
 	}
 	else variogram = new GaussianVariogram(options);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 13101)
@@ -52,5 +52,5 @@
 	double  T,rho,sl,tc,mc;
 
-	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -123,5 +123,5 @@
 		if(flag) _pprintLine_("Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error2_("Sign should be either +1 or -1.\n");
+	else _error_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units){
+void MassFluxx(IssmDouble* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units){
 
 	int i,j;
@@ -20,11 +20,11 @@
 	
 	/*output: */
-	double mass_flux=0;
-	double all_mass_flux=0;
+	IssmDouble mass_flux=0;
+	IssmDouble all_mass_flux=0;
 
 	int  counter;
 
 	/*all segments: */
-	double** array=NULL;
+	IssmDouble** array=NULL;
 	int      M;
 	int*     mdims_array=NULL;
@@ -32,5 +32,5 @@
 
 	/*our segments of interest: */
-	double*  segments=NULL;
+	IssmDouble*  segments=NULL;
 	int      num_segments;
 
@@ -48,5 +48,5 @@
 	 * When we find one, use the element to compute the mass flux on the segment: */
 	for(i=0;i<num_segments;i++){
-		element_id=(int)*(segments+5*i+4);
+		element_id=reCast<int,IssmDouble>(*(segments+5*i+4));
 		for(j=0;j<elements->Size();j++){
 			element=(Element*)elements->GetObjectByOffset(j);
@@ -66,10 +66,10 @@
 	/*Free ressources:*/
 	for(j=0;j<M;j++){
-		double* matrix=array[j];
-		xDelete<double>(matrix);
+		IssmDouble* matrix=array[j];
+		xDelete<IssmDouble>(matrix);
 	}
 	xDelete<int>(mdims_array);
 	xDelete<int>(ndims_array);
-	xDelete<double*>(array);
+	xDelete<IssmDouble*>(array);
 	
 	/*Assign output pointers: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units);
+void MassFluxx(IssmDouble* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units);
 
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVxx( IssmDouble* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvx;
-	double node_maxabsvx;
-	double element_maxabsvx;
+	IssmDouble maxabsvx;
+	IssmDouble node_maxabsvx;
+	IssmDouble element_maxabsvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVxx( IssmDouble* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVyx( IssmDouble* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvy;
-	double node_maxabsvy;
-	double element_maxabsvy;
+	IssmDouble maxabsvy;
+	IssmDouble node_maxabsvy;
+	IssmDouble element_maxabsvy;
 
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVyx( IssmDouble* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVYX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVzx( IssmDouble* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvz;
-	double node_maxabsvz;
-	double element_maxabsvz;
+	IssmDouble maxabsvz;
+	IssmDouble node_maxabsvz;
+	IssmDouble element_maxabsvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVzx( IssmDouble* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVZX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 13101)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVelx( IssmDouble* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvel;
-	double node_maxvel;
-	double element_maxvel;
+	IssmDouble maxvel;
+	IssmDouble node_maxvel;
+	IssmDouble element_maxvel;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVelx( IssmDouble* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVELX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVxx( IssmDouble* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvx;
-	double node_maxvx;
-	double element_maxvx;
+	IssmDouble maxvx;
+	IssmDouble node_maxvx;
+	IssmDouble element_maxvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 13101)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVxx( IssmDouble* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVyx( IssmDouble* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 
 	int i;
-	double maxvy;
-	double node_maxvy;
-	double element_maxvy;
+	IssmDouble maxvy;
+	IssmDouble node_maxvy;
+	IssmDouble element_maxvy;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVyx( IssmDouble* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVYX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 13101)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVzx( IssmDouble* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvz;
-	double node_maxvz;
-	double element_maxvz;
+	IssmDouble maxvz;
+	IssmDouble node_maxvz;
+	IssmDouble element_maxvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVzx( IssmDouble* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVZX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 13101)
@@ -51,5 +51,5 @@
 			for (i=0;i<numberofnodes;i++)    npart[i]=0;
 		}
-		else _error2_("At least one processor is required");
+		else _error_("At least one processor is required");
 	}
 	else{
@@ -78,5 +78,5 @@
 			for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
 		}
-		else _error2_("At least one processor is required");
+		else _error_("At least one processor is required");
 
 		/*Extrude epart2d to epart, using numlayers: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13101)
@@ -38,5 +38,5 @@
 	if(    (edge1==IntersectEnum) && (edge2==IntersectEnum) && (edge3==IntersectEnum)   ){
 		/*This case is impossible: */
-		_error2_("error: a line cannot go through 3 different vertices!");
+		_error_("error: a line cannot go through 3 different vertices!");
 	}
 	else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp	(revision 13101)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVelx( IssmDouble* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvel;
-	double node_minvel;
-	double element_minvel;
+	IssmDouble minvel;
+	IssmDouble node_minvel;
+	IssmDouble element_minvel;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVelx( IssmDouble* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVELX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVxx( IssmDouble* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvx;
-	double node_minvx;
-	double element_minvx;
+	IssmDouble minvx;
+	IssmDouble node_minvx;
+	IssmDouble element_minvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVxx( IssmDouble* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVyx( IssmDouble* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvy;
-	double node_minvy;
-	double element_minvy;
+	IssmDouble minvy;
+	IssmDouble node_minvy;
+	IssmDouble element_minvy;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVyx( IssmDouble* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVYX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp	(revision 13101)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVzx( IssmDouble* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvz;
-	double node_minvz;
-	double element_minvz;
+	IssmDouble minvz;
+	IssmDouble node_minvz;
+	IssmDouble element_minvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVzx( IssmDouble* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVZX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13101)
@@ -42,5 +42,5 @@
 
 			/*Get left and right elements*/
-			element=(int)iomodel->Data(MeshEdgesEnum)[4*i+2]-1; //edges are [node1 node2 elem1 elem2]
+			element=reCast<int,IssmDouble>(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
 
 			/*Now, if this element is not in the partition, pass: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13101)
@@ -46,5 +46,5 @@
 
 	/*Check in 3d*/
-	if(stabilization==3 && dim==3) _error2_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
 
 	/*First fetch data: */
@@ -72,5 +72,5 @@
 
 					//Get index of the vertex on which the current node is located
-					vertex_id=(int)*(iomodel->Data(MeshElementsEnum)+3*i+j); //(Matlab indexing)
+					vertex_id=reCast<int,IssmDouble>(*(iomodel->Data(MeshElementsEnum)+3*i+j)); //(Matlab indexing)
 					io_index=vertex_id-1;                      //(C indexing)
 					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13101)
@@ -21,8 +21,8 @@
 	int         num_cm_responses;
 	int        *control_type     = NULL;
-	double     *cm_responses     = NULL;
-	double     *cm_jump          = NULL;
-	double     *optscal          = NULL;
-	double     *maxiter          = NULL;
+	IssmDouble     *cm_responses     = NULL;
+	IssmDouble     *cm_jump          = NULL;
+	IssmDouble     *optscal          = NULL;
+	IssmDouble     *maxiter          = NULL;
 
 	/*Get parameters: */
@@ -64,8 +64,8 @@
 
 		xDelete<int>(control_type);
-		xDelete<double>(cm_responses);
-		xDelete<double>(cm_jump);
-		xDelete<double>(optscal);
-		xDelete<double>(maxiter);
+		xDelete<IssmDouble>(cm_responses);
+		xDelete<IssmDouble>(cm_jump);
+		xDelete<IssmDouble>(optscal);
+		xDelete<IssmDouble>(maxiter);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13101)
@@ -42,5 +42,5 @@
 	iomodel->FetchData(4,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 	for(i=0;i<num_control_type;i++){
-		switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+		switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
 			case BalancethicknessThickeningRateEnum: iomodel->FetchData(1,BalancethicknessThickeningRateEnum); break;
 			case VxEnum:   iomodel->FetchData(1,VxEnum); break;
@@ -49,5 +49,5 @@
 			case MaterialsRheologyBbarEnum:    iomodel->FetchData(1,MaterialsRheologyBEnum); break;
 			case MaterialsRheologyZbarEnum:    iomodel->FetchData(1,MaterialsRheologyZEnum); break;
-			default: _error_("Control %s not implemented yet",EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]));
+			default: _error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 13101)
@@ -124,5 +124,5 @@
 
 		default:
-			_error2_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
+			_error_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13101)
@@ -36,4 +36,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIshutterEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsmacayealpattynEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsl1l2Enum));
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsstokesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
@@ -85,6 +86,4 @@
 	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(AutodiffForwardEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(AutodiffReverseEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(QmuIsdakotaEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(InversionIscontrolEnum));
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13101)
@@ -153,5 +153,5 @@
 			/*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */ 
 			iomodel->FetchData(&array,&mdims_array,&ndims_array,&qmu_mass_flux_num_profiles,QmuMassFluxSegmentsEnum);
-			if(qmu_mass_flux_num_profiles==0)_error2_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
+			if(qmu_mass_flux_num_profiles==0)_error_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
 
 			/*Go through segments, and extract those that belong to this cpu: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13101)
@@ -16,28 +16,28 @@
 	int     i,j;
 	int     count;
-	double  yts;
-	double  g;
-	double  rho_ice;
-	double  stokesreconditioning;
-	bool    isstokes,ismacayealpattyn;
+	IssmDouble  yts;
+	IssmDouble  g;
+	IssmDouble  rho_ice;
+	IssmDouble  stokesreconditioning;
+	bool    isstokes,isl1l2,ismacayealpattyn;
    bool    spcpresent=false;
 	int Mx,Nx;
 	int My,Ny;
 	int Mz,Nz;
-	double *spcvx          = NULL;
-	double *spcvy          = NULL;
-	double *spcvz          = NULL;
-	double *nodeonmacayeal = NULL;
-	double *nodeonpattyn   = NULL;
-	double *nodeonstokes   = NULL;
-	double *nodeonbed      = NULL;
-	double *nodeonicesheet = NULL;
-	double *vertices_type  = NULL;
-	double *surface        = NULL;
-	double *z              = NULL;
-	double *timesx=NULL;
-	double *timesy=NULL;
-	double *timesz=NULL;
-   double* values=NULL;
+	IssmDouble *spcvx          = NULL;
+	IssmDouble *spcvy          = NULL;
+	IssmDouble *spcvz          = NULL;
+	IssmDouble *nodeonmacayeal = NULL;
+	IssmDouble *nodeonpattyn   = NULL;
+	IssmDouble *nodeonstokes   = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *nodeonicesheet = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *surface        = NULL;
+	IssmDouble *z              = NULL;
+	IssmDouble *timesx=NULL;
+	IssmDouble *timesy=NULL;
+	IssmDouble *timesz=NULL;
+   IssmDouble* values=NULL;
 
 	/*Output*/
@@ -56,4 +56,5 @@
 	iomodel->Constant(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 
@@ -65,5 +66,5 @@
 	
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if (!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*pconstraints=constraints;
 		return;
@@ -87,5 +88,5 @@
 
 	/*figure out times: */
-	timesx=xNew<double>(Nx);
+	timesx=xNew<IssmDouble>(Nx);
 	for(j=0;j<Nx;j++){
 		timesx[j]=spcvx[(Mx-1)*Nx+j];
@@ -94,5 +95,5 @@
 	UnitConversion(timesx,Nx,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesy=xNew<double>(Ny);
+	timesy=xNew<IssmDouble>(Ny);
 	for(j=0;j<Ny;j++){
 		timesy[j]=spcvy[(My-1)*Ny+j];
@@ -101,5 +102,5 @@
 	UnitConversion(timesy,Ny,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesz=xNew<double>(Nz);
+	timesz=xNew<IssmDouble>(Nz);
 	for(j=0;j<Nz;j++){
 		timesz[j]=spcvz[(Mz-1)*Nz+j];
@@ -113,7 +114,7 @@
 
 			/*Start with adding spcs of coupling: zero at the border macayeal/pattyn for the appropriate dofs*/
-			if ((int)vertices_type[i]==MacAyealPattynApproximationEnum){
+			if (reCast<int,IssmDouble>(vertices_type[i]==MacAyealPattynApproximationEnum)){
 				/*If grionmacayeal, spc pattyn dofs: 3 & 4*/
-					if ((int)nodeonpattyn[i]){
+					if (reCast<int,IssmDouble>(nodeonpattyn[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -130,5 +131,5 @@
 
 					}
-					else if ((int)nodeonmacayeal[i]){
+					else if (reCast<int,IssmDouble>(nodeonmacayeal[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -145,10 +146,10 @@
 
 					}
-					else _error2_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
+					else _error_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
 			}
 			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
-			else if ((int)vertices_type[i]==PattynStokesApproximationEnum){
+			else if (reCast<int,IssmDouble>(vertices_type[i])==PattynStokesApproximationEnum){
 				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
-					if ((int)nodeonpattyn[i]){
+					if (reCast<int,IssmDouble>(nodeonpattyn[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -167,5 +168,5 @@
 
 					}
-					else if ((int)nodeonstokes[i]){ //spc pattyn nodes: 1 & 2
+					else if (reCast<int,IssmDouble>(nodeonstokes[i])){ //spc pattyn nodes: 1 & 2
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -185,10 +186,10 @@
 						}
 					}
-					else _error2_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
+					else _error_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
 			}
 			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
-			else if ((int)vertices_type[i]==MacAyealStokesApproximationEnum){
+			else if (reCast<int,IssmDouble>(vertices_type[i])==MacAyealStokesApproximationEnum){
 				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
-					if ((int)nodeonmacayeal[i]){
+					if (reCast<int,IssmDouble>(nodeonmacayeal[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -207,5 +208,5 @@
 
 					}
-					else if ((int)nodeonstokes[i]){ //spc macayeal nodes: 1 & 2
+					else if (reCast<int,IssmDouble>(nodeonstokes[i])){ //spc macayeal nodes: 1 & 2
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -225,5 +226,5 @@
 						}
 					}
-					else _error2_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
+					else _error_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
 			}
 			/*Now add the regular spcs*/
@@ -235,5 +236,5 @@
 				else if (Mx==numberofvertices+1) {
 					/*figure out times and values: */
-					values=xNew<double>(Nx);
+					values=xNew<IssmDouble>(Nx);
 					spcpresent=false;
 					for(j=0;j<Nx;j++){
@@ -246,5 +247,5 @@
 						count++;
 					}
-					xDelete<double>(values);
+					xDelete<IssmDouble>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -259,5 +260,5 @@
 				else if (My==numberofvertices+1){
 					/*figure out times and values: */
-					values=xNew<double>(Ny);
+					values=xNew<IssmDouble>(Ny);
 					spcpresent=false;
 					for(j=0;j<Ny;j++){
@@ -269,5 +270,5 @@
 						count++;
 					}
-					xDelete<double>(values);
+					xDelete<IssmDouble>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -276,5 +277,5 @@
 				}
 
-				if ((int)vertices_type[i]==StokesApproximationEnum ||  ((int)vertices_type[i]==NoneApproximationEnum)){
+				if (reCast<int,IssmDouble>(vertices_type[i])==StokesApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
 					if (Mz==numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
@@ -283,5 +284,5 @@
 					else if (Mz==numberofvertices+1){
 						/*figure out times and values: */
-						values=xNew<double>(Nz);
+						values=xNew<IssmDouble>(Nz);
 						spcpresent=false;
 						for(j=0;j<Nz;j++){
@@ -293,9 +294,9 @@
 							count++;
 						}
-						xDelete<double>(values);
-					}
-
-				}
-				if ((int)vertices_type[i]==NoneApproximationEnum){
+						xDelete<IssmDouble>(values);
+					}
+
+				}
+				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,g*rho_ice*(surface[i]-z[i])/stokesreconditioning,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
 					count++;
@@ -304,6 +305,6 @@
 
 			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
-			if (dim==3) if(nodeonbed[i] && nodeonicesheet[i] && nodeonstokes[i]){
-				 switch((int)vertices_type[i]){
+			if (dim==3) if(reCast<int,IssmDouble>(nodeonbed[i]) && reCast<int,IssmDouble>(nodeonicesheet[i]) && reCast<int,IssmDouble>(nodeonstokes[i])){
+				 switch(reCast<int,IssmDouble>(vertices_type[i])){
 					case MacAyealStokesApproximationEnum:
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,DiagnosticHorizAnalysisEnum));
@@ -318,5 +319,5 @@
 						count++;
 						break;
-					default: _error2_("Vertex approximation " << EnumToStringx((int)vertices_type[i]) << " not supported");
+					default: _error_("Vertex approximation " << EnumToStringx(reCast<int,IssmDouble>(vertices_type[i])) << " not supported");
 				}
 			}
@@ -325,21 +326,21 @@
 	  
 	/*Free data: */
-	xDelete<double>(spcvx);
-	xDelete<double>(spcvy);
-	xDelete<double>(spcvz);
-	xDelete<double>(nodeonmacayeal);
-	xDelete<double>(nodeonpattyn);
-	xDelete<double>(nodeonstokes);
-	xDelete<double>(nodeonicesheet);
-	xDelete<double>(nodeonbed);
-	xDelete<double>(vertices_type);
-	xDelete<double>(surface);
-	xDelete<double>(z);
+	xDelete<IssmDouble>(spcvx);
+	xDelete<IssmDouble>(spcvy);
+	xDelete<IssmDouble>(spcvz);
+	xDelete<IssmDouble>(nodeonmacayeal);
+	xDelete<IssmDouble>(nodeonpattyn);
+	xDelete<IssmDouble>(nodeonstokes);
+	xDelete<IssmDouble>(nodeonicesheet);
+	xDelete<IssmDouble>(nodeonbed);
+	xDelete<IssmDouble>(vertices_type);
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(z);
 
 	/*Free resources:*/
-	xDelete<double>(timesx);
-	xDelete<double>(timesy);
-	xDelete<double>(timesz);
-	xDelete<double>(values);
+	xDelete<IssmDouble>(timesx);
+	xDelete<IssmDouble>(timesy);
+	xDelete<IssmDouble>(timesz);
+	xDelete<IssmDouble>(values);
 
 	/*Assign output pointer: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13101)
@@ -27,19 +27,20 @@
 	int dim;
 	int numberofvertices;
-	bool ismacayealpattyn,isstokes;
+	bool ismacayealpattyn,isstokes,isl1l2;
 	int  numpenalties,numberofpressureloads,numrifts,numriftsegments;
-	double *pressureload   = NULL;
-	double *elements_type  = NULL;
-	double *nodeoniceshelf = NULL;
-	double *riftinfo       = NULL;
-	double *nodeonbed      = NULL;
-	double *nodeonstokes   = NULL;
-	double *nodeonicesheet = NULL;
-	double *vertices_type  = NULL;
-	double *penalties      = NULL;
+	IssmDouble *pressureload   = NULL;
+	IssmDouble *elements_type  = NULL;
+	IssmDouble *nodeoniceshelf = NULL;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *nodeonstokes   = NULL;
+	IssmDouble *nodeonicesheet = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *penalties      = NULL;
 
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
@@ -53,5 +54,5 @@
 
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if (!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*ploads=loads;
 		return;
@@ -73,5 +74,5 @@
 		if (dim==2) segment_width=4; 
 		else segment_width=6;
-		element=(int)(*(pressureload+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
+		element=reCast<int,IssmDouble>(*(pressureload+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
 
 		/*Now, if this element is not in the partition, pass: */
@@ -79,24 +80,32 @@
 		
 		/*Do not create ice front if Hutter or Stokes elements*/
-		if ((int)*(elements_type+element)==HutterApproximationEnum) continue;
+		if (reCast<int,IssmDouble>(*(elements_type+element))==HutterApproximationEnum) continue;
 
 		/*Create and  add load: */
-		if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==2){
+		if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealApproximationEnum) && dim==2){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal2dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==3){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealApproximationEnum) && dim==3){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(PattynApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(L1L2ApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(PattynApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(StokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(L1L2ApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,L1L2IceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(StokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,StokesIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealPattynApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealPattynApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -104,5 +113,5 @@
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(PattynStokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(PattynStokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -110,5 +119,5 @@
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealStokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealStokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -120,6 +129,6 @@
 	/*Free data: */
 	iomodel->DeleteData(3,DiagnosticIcefrontEnum,ThicknessEnum,BedEnum);
-	xDelete<double>(elements_type);
-	xDelete<double>(pressureload);
+	xDelete<IssmDouble>(elements_type);
+	xDelete<IssmDouble>(pressureload);
 
 	/*Create Penpair for penalties: */
@@ -128,5 +137,5 @@
 	for(i=0;i<numpenalties;i++){
 
-		if(iomodel->my_vertices[(int)penalties[2*i+0]-1]){
+		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
 
 			/*In debugging mode, check that the second node is in the same cpu*/
@@ -134,6 +143,6 @@
 
 			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+(int)penalties[2*i+0];
-			penpair_ids[1]=iomodel->nodecounter+(int)penalties[2*i+1];
+			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
 
 			/*Create Load*/
@@ -144,5 +153,5 @@
 
 	/*free ressources: */
-	xDelete<double>(penalties);
+	xDelete<IssmDouble>(penalties);
 
 	/*Create Riffront loads for rifts: */
@@ -151,5 +160,5 @@
 		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
 		for(i=0;i<numriftsegments;i++){
-			if(iomodel->my_elements[(int)*(riftinfo+RIFTINFOSIZE*i+2)-1]){
+			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
 				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,DiagnosticHorizAnalysisEnum));
 				count++;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13101)
@@ -19,5 +19,5 @@
 	bool   continuous_galerkin=true;
 	int    numberofvertices;
-	bool   isstokes,ismacayealpattyn;
+	bool   isstokes,isl1l2,ismacayealpattyn;
 
 	/*DataSets: */
@@ -27,4 +27,5 @@
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 
@@ -36,5 +37,5 @@
 	
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if(!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*pnodes=nodes;
 		return;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13101)
@@ -19,4 +19,5 @@
 	int    numberofelements;
 	bool   ismacayealpattyn;
+	bool   isl1l2;
 	bool   isstokes;
 	bool   control_analysis;
@@ -25,4 +26,5 @@
 	/*Fetch constants needed: */
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -32,5 +34,5 @@
 
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if(!ismacayealpattyn & !isstokes) return;
+	if(!ismacayealpattyn & !isstokes &!isl1l2) return;
 
 	/*Fetch data needed: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13101)
@@ -16,5 +16,5 @@
 	int i;
 	int count;
-	double yts;
+	IssmDouble yts;
 	int    numberofvertices;
 	bool   ishutter;
@@ -51,5 +51,5 @@
 		/*keep only this partition's nodes:*/
 		if((iomodel->my_vertices[i])){
-			if (!(int)iomodel->Data(FlowequationVertexEquationEnum)[i]==HutterApproximationEnum){
+			if (!reCast<int,IssmDouble>(iomodel->Data(FlowequationVertexEquationEnum)[i])==HutterApproximationEnum){
 
 				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHutterAnalysisEnum));
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13101)
@@ -17,5 +17,5 @@
 	int dim;
 	int count;
-	double yts;
+	IssmDouble yts;
 	int    numberofvertices;
 
@@ -52,5 +52,5 @@
 		if(iomodel->my_vertices[i]){
 
-			if ((int)iomodel->Data(FlowequationBorderstokesEnum)[i]){
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationBorderstokesEnum)[i])){
 				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticVertAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for Stokes
 				count++;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13101)
@@ -19,4 +19,7 @@
 	if (analysis_type==DiagnosticHorizAnalysisEnum){
 		if (vertices_type[0]==MacAyealApproximationEnum){
+			numdofs=2;
+		}
+		else if (vertices_type[0]==L1L2ApproximationEnum){
 			numdofs=2;
 		}
@@ -61,5 +64,5 @@
 			doftype[5]=StokesApproximationEnum;
 		}
-		else _error2_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
+		else _error_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
 	}
 	else if (analysis_type==DiagnosticVertAnalysisEnum){
@@ -90,5 +93,5 @@
 		numdofs=1;
 	}
-	else _error2_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
+	else _error_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
 
 	/*Now initialize the index*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13101)
@@ -21,6 +21,6 @@
 	int    numberofvertices;
 	bool   spcpresent=false;
-	double heatcapacity;
-	double referencetemperature;
+	IssmDouble heatcapacity;
+	IssmDouble referencetemperature;
 	
 	/*Output*/
@@ -106,5 +106,5 @@
 	}
 	else{
-		_error2_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13101)
@@ -26,5 +26,5 @@
 
 	/*if 2d: Error*/
-	if (dim==2) _error2_("2d meshes not supported yet");
+	if (dim==2) _error_("2d meshes not supported yet");
 
 	/*Recover pointer: */
@@ -40,5 +40,5 @@
 	for (i=0;i<numberofvertices;i++){
 		if((iomodel->my_vertices[i]==1)){
-			if (iomodel->Data(MeshVertexonbedEnum)[i]){ 
+			if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
 				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,MeltingAnalysisEnum));
 			}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13101)
@@ -103,5 +103,5 @@
 	}
 	else{
-		_error2_("not implemented yet");
+		_error_("not implemented yet");
 	}
 
@@ -111,5 +111,5 @@
 	iomodel->FetchData(&edges,&numberofedges,&cols,MeshEdgesEnum);
 	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
-	if (cols!=4) _error2_("field edges should have 4 columns");
+	if (cols!=4) _error_("field edges should have 4 columns");
 
 	/*!All elements have been partitioned above, only create elements for this CPU: */
@@ -152,5 +152,5 @@
 			}
 			else{
-				_error2_("Problem in edges creation");
+				_error_("Problem in edges creation");
 			}
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13101)
@@ -46,5 +46,5 @@
 
 	/*Check in 3d*/
-	if(stabilization==3 && dim==3) _error2_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
 
 	/*First fetch data: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13101)
@@ -23,5 +23,4 @@
 	bool   ispdd;
 	bool   isdelta18o;
-	IssmDouble *size, Delta18oTimeSerie,Delta18oSurfaceTimeSerie ;
 
 	/*Fetch data needed: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13101)
@@ -33,5 +33,5 @@
 
 	/*return if 2d mesh*/
-	if (dim==2) _error2_("2d meshes not supported yet");
+	if (dim==2) _error_("2d meshes not supported yet");
 
 	//create penalties for nodes: no node can have a temperature over the melting point
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13101)
@@ -38,5 +38,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error2_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
+	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
 	#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13101)
@@ -71,5 +71,5 @@
 	 * warn the user to increase the connectivity width: */
 	for(i=0;i<nods;i++){
-		if (*(connectivity+width*i+maxels)>maxels)_error2_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
+		if (*(connectivity+width*i+maxels)>maxels)_error_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp	(revision 13101)
@@ -11,5 +11,5 @@
 
 	/*intermediary:*/
-	double norm_new,norm_old,dot_product;;
+	IssmDouble norm_new,norm_old,dot_product;;
 
 	/*Initialize output*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13101)
@@ -106,5 +106,5 @@
 		char* string=strings[i];
 		if(my_rank==0){
-			if(string==NULL) _error2_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
+			if(string==NULL) _error_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
 		}
 		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 	 * management routine, otherwise, skip : */
 	if (RiftIsPresent(loads,analysis_type)){
-		_error2_("rift constraints reset not supported yet!");
+		_error_("rift constraints reset not supported yet!");
 	}
 	else if(ThermalIsPresent(loads,analysis_type)){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 13101)
@@ -49,7 +49,7 @@
 		case VelEnum:ElementResponsex(responses, elements,nodes, vertices, loads, materials, parameters,VelEnum,process_units); break;
 		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
-		default: _error2_("response descriptor \"" << response_descriptor << "\" not supported yet!"); break;
+		default: _error_("response descriptor \"" << response_descriptor << "\" not supported yet!"); break;
 		#else
-		default: _error2_("ISSM was not compiled with responses capabilities, exiting!");
+		default: _error_("ISSM was not compiled with responses capabilities, exiting!");
 		#endif
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13101)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector){
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector){
 
 	int  num_controls;
@@ -30,5 +30,5 @@
 void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* vector){
 	
-	double* serial_vector=NULL;
+	IssmDouble* serial_vector=NULL;
 
 	serial_vector=vector->ToMPISerial();
@@ -37,4 +37,4 @@
 
 	/*Free ressources:*/
-	xDelete<double>(serial_vector);
+	xDelete<IssmDouble>(serial_vector);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 13101)
@@ -10,5 +10,5 @@
 /* local prototypes: */
 void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* vector);
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector);
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector);
 
 #endif 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13101)
@@ -75,5 +75,5 @@
 
 	hSHP = SHPOpen( filshp, "rb" );
-	if (!hSHP) _error2_("Error opening shp/shx files.");
+	if (!hSHP) _error_("Error opening shp/shx files.");
 
 /*  read header and print out file bounds  */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 13101)
@@ -44,5 +44,5 @@
 			break;}
 		default:
-			  _error2_("Matrix type: " << Kff->type << " not supported yet!");
+			  _error_("Matrix type: " << Kff->type << " not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 13101)
@@ -25,4 +25,5 @@
 void SolverxSeq(SeqVec** puf,SeqMat* Kff, SeqVec* pf);
 void SolverxSeq(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n);
+void SolverxSeq(double** pX,double* A,double* B,int n);
 
 #endif  /* _SOLVERX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13101)
@@ -96,5 +96,5 @@
 		#if _PETSC_MAJOR_ >=3
 			#ifndef _HAVE_MUMPS_
-			_error2_("requested MUMPS solver, which was not compiled into ISSM!\n");
+			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
 			#endif
 		#endif
@@ -120,5 +120,5 @@
 	if (solver_type==StokesSolverEnum){
 		/*Make indices out of doftypes: */
-		if(!df)_error2_("need doftypes for Stokes solver!\n");
+		if(!df)_error_("need doftypes for Stokes solver!\n");
 		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
 
@@ -151,5 +151,5 @@
 	/*Check convergence*/
 	KSPGetIterationNumber(ksp,&iteration_number);
-	if (iteration_number<0) _error2_("Solver diverged at iteration number: " << -iteration_number);
+	if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
 
 	/*Free resources:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13101)
@@ -30,6 +30,6 @@
 	pf->GetSize(&N2);
 
-	if(N!=N2)_error2_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
-	if(M!=N)_error2_("Stiffness matrix should be square!");
+	if(N!=N2)_error_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
+	if(M!=N)_error_("Stiffness matrix should be square!");
 
 	SolverxSeq(&x,Kff->matrix,pf->vector,N);
@@ -40,50 +40,81 @@
 
 	#else
-		_error2_("GSL support not compiled in!");
+		_error_("GSL support not compiled in!");
 	#endif
 
 }/*}}}*/
-void SolverxSeq(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n){/*{{{*/
+#ifdef _HAVE_ADOLC_
+void SolverxSeq(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n){//{{{
+	/* if we use Adol-C then the IssmDouble will be an adouble
+	   and the calls to gsl_... will not work. 
+	   We therefore call a wrapped solver instead. 
+	*/
 
+	/*Output: */
+	IssmDouble* X=NULL;
+
+	/*Intermediary: */
+	int     i;
+	IssmPDouble* pdoubleA=NULL;
+	IssmPDouble* pdoubleB=NULL;
+	IssmPDouble* pdoubleX=NULL;
+
+	/*First, transfer from IssmDouble to double all our matrices and vectors: */
+	pdoubleA=xNew<double>(n*n);
+	pdoubleB=xNew<double>(n);
+	for(i=0;i<n*n;i++)pdoubleA[i]=reCast<IssmPDouble>(A[i]);
+	for(i=0;i<n;i++)pdoubleB[i]=reCast<IssmPDouble>(B[i]);
+	
+	/*Call wrapped solver: */
+	SolverxSeq(&pdoubleX,pdoubleA, pdoubleB, n);
+
+	/*Transfer solution vector from double to IssmDouble: */
+	X = xNew<IssmDouble>(n);
+	for(i=0;i<n;i++)X[i]=reCast<IssmDouble>(pdoubleX[i]);
+
+	/*Free ressources:*/
+	xDelete<IssmPDouble>(pdoubleA);
+	xDelete<IssmPDouble>(pdoubleB);
+
+	/*Assign output pointers: */
+	*pX=X;
+}
+/*}}}*/
+#endif
+void SolverxSeq(IssmPDouble** pX,IssmPDouble* A,IssmPDouble* B,int n){ //{{{
 	#ifdef _HAVE_GSL_
-		/*GSL Matrices and vectors: */
-		int              s;
-		gsl_matrix_view  a;
-		gsl_vector_view  b;
-		gsl_vector      *x = NULL;
-		gsl_permutation *p = NULL;
-		#ifdef _HAVE_ADOLC_
-			// if we use Adol-C then the IssmDouble will be an adouble
-			// and the calls to gsl_... will not work
-			// and we should call  a suitable wrapped solve instead
-			_error2_("SolverxSeq: should not be here with Adol-C");
-		#else
-			/*A will be modified by LU decomposition. Use copy*/
-			IssmDouble* Acopy = xNew<IssmDouble>(n*n);
-			xMemCpy<IssmDouble>(Acopy,A,n*n);
+	/*GSL Matrices and vectors: */
+	int              s;
+	gsl_matrix_view  a;
+	gsl_vector_view  b;
+	gsl_vector      *x = NULL;
+	gsl_permutation *p = NULL;
+	/*A will be modified by LU decomposition. Use copy*/
+	double* Acopy = xNew<double>(n*n);
+	xMemCpy<double>(Acopy,A,n*n);
 
-			/*Initialize gsl matrices and vectors: */
-			a = gsl_matrix_view_array (Acopy,n,n);
-			b = gsl_vector_view_array (B,n);
-			x = gsl_vector_alloc (n);
+	/*Initialize gsl matrices and vectors: */
+	a = gsl_matrix_view_array (Acopy,n,n);
+	b = gsl_vector_view_array (B,n);
+	x = gsl_vector_alloc (n);
 
-			/*Run LU and solve: */
-			p = gsl_permutation_alloc (n);
-			gsl_linalg_LU_decomp (&a.matrix, p, &s);
-			gsl_linalg_LU_solve (&a.matrix, p, &b.vector, x);
+	/*Run LU and solve: */
+	p = gsl_permutation_alloc (n);
+	gsl_linalg_LU_decomp (&a.matrix, p, &s);
+	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, x);
 
-			//printf ("x = \n");
-			//gsl_vector_fprintf (stdout, x, "%g");
+	//printf ("x = \n");
+	//gsl_vector_fprintf (stdout, x, "%g");
 
-			/*Copy result*/
-			IssmDouble* X = xNew<IssmDouble>(n);
-			memcpy(X,gsl_vector_ptr(x,0),n*sizeof(IssmDouble));
+	/*Copy result*/
+	double* X = xNew<double>(n);
+	memcpy(X,gsl_vector_ptr(x,0),n*sizeof(double));
 
-			/*Clean up and assign output pointer*/
-			xDelete<IssmDouble>(Acopy);
-			gsl_permutation_free(p);
-			gsl_vector_free(x);
-			*pX=X;
-		#endif
+	/*Clean up and assign output pointer*/
+	xDelete<double>(Acopy);
+	gsl_permutation_free(p);
+	gsl_vector_free(x);
+	*pX=X;
 	#endif
-}/*}}}*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13101)
@@ -18,7 +18,5 @@
 
    if(stage==1){
-	      if (strcmp(name,"AutodiffForward")==0) return AutodiffForwardEnum;
-	      else if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
-	      else if (strcmp(name,"AutodiffReverse")==0) return AutodiffReverseEnum;
+	      if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
 	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
 	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
@@ -56,4 +54,5 @@
 	      else if (strcmp(name,"FlowequationElementEquation")==0) return FlowequationElementEquationEnum;
 	      else if (strcmp(name,"FlowequationIshutter")==0) return FlowequationIshutterEnum;
+	      else if (strcmp(name,"FlowequationIsl1l2")==0) return FlowequationIsl1l2Enum;
 	      else if (strcmp(name,"FlowequationIsmacayealpattyn")==0) return FlowequationIsmacayealpattynEnum;
 	      else if (strcmp(name,"FlowequationIsstokes")==0) return FlowequationIsstokesEnum;
@@ -138,9 +137,9 @@
 	      else if (strcmp(name,"MiscellaneousName")==0) return MiscellaneousNameEnum;
 	      else if (strcmp(name,"PrognosticHydrostaticAdjustment")==0) return PrognosticHydrostaticAdjustmentEnum;
+	      else if (strcmp(name,"PrognosticMinThickness")==0) return PrognosticMinThicknessEnum;
          else stage=2;
    }
    if(stage==2){
-	      if (strcmp(name,"PrognosticMinThickness")==0) return PrognosticMinThicknessEnum;
-	      else if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
+	      if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
 	      else if (strcmp(name,"PrognosticSpcthickness")==0) return PrognosticSpcthicknessEnum;
 	      else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
@@ -243,9 +242,10 @@
 	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
 	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
+	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
 	      else if (strcmp(name,"HutterApproximation")==0) return HutterApproximationEnum;
 	      else if (strcmp(name,"MacAyealApproximation")==0) return MacAyealApproximationEnum;
 	      else if (strcmp(name,"MacAyealPattynApproximation")==0) return MacAyealPattynApproximationEnum;
 	      else if (strcmp(name,"MacAyealStokesApproximation")==0) return MacAyealStokesApproximationEnum;
-	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
+	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
 	      else if (strcmp(name,"PattynApproximation")==0) return PattynApproximationEnum;
 	      else if (strcmp(name,"PattynStokesApproximation")==0) return PattynStokesApproximationEnum;
@@ -290,4 +290,5 @@
 	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
 	      else if (strcmp(name,"Param")==0) return ParamEnum;
+	      else if (strcmp(name,"L1L2IceFront")==0) return L1L2IceFrontEnum;
 	      else if (strcmp(name,"PattynIceFront")==0) return PattynIceFrontEnum;
 	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
@@ -383,9 +384,11 @@
 	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
 	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
-	      else if (strcmp(name,"StepResponses")==0) return StepResponsesEnum;
          else stage=4;
    }
    if(stage==4){
-	      if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
+	      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;
 	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
@@ -406,8 +409,4 @@
 	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
-	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
-	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
-	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
-	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
 	      else if (strcmp(name,"P0")==0) return P0Enum;
 	      else if (strcmp(name,"P1")==0) return P1Enum;
@@ -443,4 +442,6 @@
 	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
 	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
 	      else if (strcmp(name,"Relative")==0) return RelativeEnum;
 	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
@@ -492,4 +493,4 @@
    }
 	/*If we reach this point, the string provided has not been found*/
-	_error2_("Enum " << name << " not found");
+	_error_("Enum " << name << " not found");
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13101)
@@ -11,5 +11,5 @@
 #include "../SurfaceAreax/SurfaceAreax.h"
 
-void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -18,6 +18,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute surface area and add to elements inputs */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAcrossGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void ThicknessAcrossGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13101)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAlongGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void ThicknessAlongGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 13101)
@@ -10,8 +10,8 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void TotalSmbx(double* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void TotalSmbx(IssmDouble* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 
-	double local_smb = 0;
-	double total_smb;
+	IssmDouble local_smb = 0;
+	IssmDouble total_smb;
 
 	for(int i=0;i<elements->Size();i++){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 13101)
@@ -10,5 +10,5 @@
 
 /* local prototypes: */
-void TotalSmbx(double* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void TotalSmbx(IssmDouble* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 13101)
@@ -53,5 +53,5 @@
 	double  sl,rho,cm,T,chi;
 
-	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -131,5 +131,5 @@
 		if(flag) _pprintLine_("Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error2_("Sign should be either +1 or -1.\n");
+	else _error_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp	(revision 13101)
@@ -27,9 +27,9 @@
 	if (size==0){
 		function();
-		_error2_("usage: see above");
+		_error_("usage: see above");
 	}
 	else if (size!=NRHS ) {
 		function(); 
-		_error2_("usage error.");
+		_error_("usage error.");
 	}
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp	(revision 13101)
@@ -48,5 +48,5 @@
 	
 	/*check this is indeed a subtype of long type: */
-	if(!PyBool_Check(py_boolean))_error2_("expecting a boolean in input!");
+	if(!PyBool_Check(py_boolean))_error_("expecting a boolean in input!");
 
 	/*extract boolean: */
@@ -69,5 +69,5 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
-	if(ndim!=2)_error2_("expecting an MxN matrix in input!");
+	if(ndim!=2)_error_("expecting an MxN matrix in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_matrix);
 	M=dims[0]; N=dims[1];
@@ -97,5 +97,5 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
-	if(ndim!=2)_error2_("expecting an MxN matrix in input!");
+	if(ndim!=2)_error_("expecting an MxN matrix in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_matrix);
 	M=dims[0]; N=dims[1];
@@ -125,5 +125,5 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
-	if(ndim!=1)_error2_("expecting an Mx1 vector in input!");
+	if(ndim!=1)_error_("expecting an Mx1 vector in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_vector);
 	M=dims[0]; 
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp	(revision 13101)
@@ -21,4 +21,10 @@
 
 
+/*FUNCTION WriteData(PyObject* py_tuple,int index,int integer){{{*/
+void WriteData(PyObject* py_tuple, int index, int integer){
+	
+	PyTuple_SetItem(py_tuple, index, PyInt_FromSsize_t(integer));
+
+}/*}}}*/
 /*FUNCTION WriteData(PyObject* py_tuple,int index,char* string){{{*/
 void WriteData(PyObject* py_tuple, int index, char* string){
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h	(revision 13101)
@@ -28,4 +28,5 @@
 //void WriteData(DataHandle* py_tuple,Parameters* parameters);
 void WriteData(PyObject* py_tuple, int index, double* matrix, int M,int N);
+void WriteData(PyObject* py_tuple, int index, int integer);
 void WriteData(PyObject* py_tuple, int index, char* string);
 void WriteData(PyObject* py_tuple, int index, Matrix* matrix);
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 13101)
@@ -31,9 +31,9 @@
 	void* memptr=NULL;
 
-	if(!size)_error2_("attempting to 0 size allocation!");
+	if(!size)_error_("attempting to 0 size allocation!");
 
 	/* Use the c library to do the allocation: */
 	memptr=malloc(size);
-	if(!memptr) _error2_("memory allocation failed!");
+	if(!memptr) _error_("memory allocation failed!");
 
 	return memptr;
@@ -44,9 +44,9 @@
 	void* memptr=NULL;
 	
-	if(!size)_error2_("attempting to 0 size allocation!");
+	if(!size)_error_("attempting to 0 size allocation!");
 
 	/* Use the c library to do the allocation: */
 	memptr=calloc(n,size);
-	if(!memptr) _error2_("memory allocation failed!");
+	if(!memptr) _error_("memory allocation failed!");
 
 	return memptr;
@@ -88,9 +88,9 @@
 	register void* value=NULL;
 	
-	if(!size)_error2_("attempting to realloc to zero");
+	if(!size)_error_("attempting to realloc to zero");
 	value = (void*)realloc(pv,size);
 
 	if (value == NULL) {
-		_error2_("virtual memory exhausted");
+		_error_("virtual memory exhausted");
 	}
 	return value;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 13101)
@@ -22,5 +22,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
@@ -67,5 +67,5 @@
 				break;
 			default:
-				_error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+				_error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13101)
@@ -80,5 +80,5 @@
       if (tstar < PDup){
 	pd = 1.;
-	if (tstar >= -siglimc){ pd = pds[int(tstar/DT + siglim0c)];}}
+	if (tstar >= -siglimc){ pd = pds[reCast<int,IssmDouble>(tstar/DT + siglim0c)];}}
       else { 
 	pd = 0.;}
@@ -100,5 +100,5 @@
       if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
       else if (tstar> -siglim){
-	pddsig=pdds[int(tstar/DT + siglim0)];
+	pddsig=pdds[reCast<int,IssmDouble>(tstar/DT + siglim0)];
 	pdd = pdd + pddsig*deltm;
 	frzndd = frzndd - (tstar-pddsig)*deltm;}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 13101)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13101)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 13101)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 13101)
@@ -39,5 +39,5 @@
 	/*open domain outline file for reading: */
 	if ((fid=fopen(domainname,"r"))==NULL){
-		_error2_("could not find domain file " << domainname); 
+		_error_("could not find domain file " << domainname); 
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13101)
@@ -23,5 +23,5 @@
 	/*open domain outline file for writing: */
 	if ((fid=fopen(domainname,"w"))==NULL){
-		_error2_("could not open domain file " << domainname); 
+		_error_("could not open domain file " << domainname); 
 		noerr=0; goto cleanupandreturn;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 13101)
@@ -36,5 +36,5 @@
 	if (!itrnb) {
 		if (nrowb != idimb) {
-			_error2_("Matrix A and B inner vectors not equal size.");
+			_error_("Matrix A and B inner vectors not equal size.");
 		}
 		idimc=ncolb;
@@ -42,5 +42,5 @@
 	else {
 		if (ncolb != idimb) {
-			_error2_("Matrix A and B inner vectors not equal size.");
+			_error_("Matrix A and B inner vectors not equal size.");
 		}
 		idimc=nrowb;
@@ -49,5 +49,5 @@
 	if (!itrnc) {
 		if (nrowc != idimc) {
-			_error2_("Matrix B and C inner vectors not equal size.");
+			_error_("Matrix B and C inner vectors not equal size.");
 		}
 		idimd=ncolc;
@@ -55,5 +55,5 @@
 	else {
 		if (ncolc != idimc) {
-			_error2_("Matrix B and C inner vectors not equal size.");
+			_error_("Matrix B and C inner vectors not equal size.");
 		}
 		idimd=nrowc;
@@ -124,5 +124,5 @@
 
 	if (ntrma != ntrmb) {
-		_error2_("Matrix A and B inner vectors not equal size");
+		_error_("Matrix A and B inner vectors not equal size");
 	    noerr=0;	
 		return noerr;
@@ -175,5 +175,5 @@
 
 	if (!b && nvec) {
-		_error2_("No right-hand side for nvec=" << nvec << ".");
+		_error_("No right-hand side for nvec=" << nvec << ".");
 		noerr=0;
 		return noerr;
@@ -214,5 +214,5 @@
 			xDelete<int>(pivrc2);
 			xDelete<int>(pindx);
-			_error2_("Pivot " << pivot << " less than machine epsilon");
+			_error_("Pivot " << pivot << " less than machine epsilon");
 			noerr=0;
 			return noerr;
@@ -349,5 +349,5 @@
 	/*Compute determinant*/
 	Matrix2x2Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
@@ -374,5 +374,5 @@
 	/*Compute determinant*/
 	Matrix3x3Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 13101)
@@ -44,5 +44,5 @@
 	iter=0;
 	fxmin = (*f)(xmin,optargs);
-	if (xIsNan<IssmDouble>(fxmin)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
 	if(VerboseControl()) _pprintLine_("");
@@ -51,5 +51,5 @@
 	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmin<<"  "<<setw(12)<<fxmin<<"           N/A         boundary");
 	fxmax = (*f)(xmax,optargs);
-	if (xIsNan<IssmDouble>(fxmax)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
 	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary");
 
@@ -75,5 +75,5 @@
 	/*2: call the function to be evaluated*/
 	fxbest = (*f)(x,optargs);
-	if(xIsNan<IssmDouble>(fxbest)) _error2_("Function evaluation returned NaN");
+	if(xIsNan<IssmDouble>(fxbest)) _error_("Function evaluation returned NaN");
 	iter=iter+1;
 
@@ -159,5 +159,5 @@
 		//evaluate function on x
 		fx = (*f)(x,optargs);
-		if(xIsNan<IssmDouble>(fx)) _error2_("Function evaluation returned NaN");
+		if(xIsNan<IssmDouble>(fx)) _error_("Function evaluation returned NaN");
 		iter=iter+1;
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 13101)
@@ -1670,5 +1670,5 @@
 		if (iter >= MAX_GAUS_ITER) {
 			xDelete<IssmPDouble>(work);
-			_error2_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
+			_error_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13101)
@@ -53,5 +53,5 @@
 		else eps=0;
 	}
-	else _error2_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
+	else _error_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13101)
@@ -41,5 +41,5 @@
 	//get the value of the function at the first boundary
 	fx1= (*f)(x1,optargs);
-	if (xIsNan<IssmDouble>(fx1)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fx1)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
 	if(VerboseControl()) _pprintLine_("");
@@ -57,5 +57,5 @@
 		iter++;
 		fx2 = (*f)(x2,optargs);
-		if (xIsNan<IssmDouble>(fx2)) _error2_("Function evaluation returned NaN");
+		if (xIsNan<IssmDouble>(fx2)) _error_("Function evaluation returned NaN");
 		if(VerboseControl())
 		 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x2<<"  "<<setw(12)<<fx2<<"  "<<(fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1)));
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13101)
@@ -57,5 +57,5 @@
 	if (found==-1){
 		/*ok, we did not find anything, this is not good! error out: */
-		_error2_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
+		_error_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 13101)
@@ -29,5 +29,5 @@
 	if(direction_enum==IuToExtEnum) for(i=0;i<numvalues;i++)values[i]=values[i]*scale; 
 	else if(direction_enum==ExtToIuEnum) for(i=0;i<numvalues;i++)values[i]=values[i]/scale; 
-	else _error2_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
+	else _error_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 13101)
@@ -34,5 +34,5 @@
 void SetVerbosityLevel(int level){
 
-	if(level<0) _error2_("vebosity level should be a positive integer (user provided " << level << ")");
+	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
 
 	verbositylevel = level;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cubic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cubic.cpp	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cubic.cpp	(revision 13101)
@@ -0,0 +1,91 @@
+#include <math.h>
+#include "./numerics.h"
+
+IssmDouble CBRT(IssmDouble Z){
+
+	IssmDouble ret;
+
+	if (Z> 0.0){
+		ret = fabs(pow(fabs(Z),1./3.));
+	}
+	else if(Z< 0.0){
+		ret = - fabs(pow(fabs(Z),1./3.));
+	}
+	else{
+		ret = 0.;
+	}
+	return ret;
+}
+
+int cubic(IssmDouble a,IssmDouble b,IssmDouble c,IssmDouble d, IssmDouble x[3], int* num){
+	/* Find the real roots of linear/quadratic and cubic equations:
+	 *
+	 *   a x^3 + bx^2 + cx + d = 0
+	 *
+	 *   returns the roots in x
+	 *   num is the number of roots */
+
+	/*Some useful constants*/
+	const IssmDouble pi    = 3.1415926535897932;
+	const IssmDouble third = 1./3.;
+
+	/*Intermediaries*/
+	IssmDouble U[3],W,P,Q,delta,phi;
+
+	/* determine the degree of the polynomial */
+	if (a != 0.0){
+		//cubic problem
+		W     = b/a *third;
+		P     = pow((c/a *third - pow(W,2)),3);
+		Q     = -.5 *(2.0*pow(W,3)-(c*W-d)/a );
+		delta = pow(Q,2)+P;
+		if ( delta < 0.0 ){
+			//three real solutions!
+			//Confine the argument of coeffCOS to the interval [-1;1]!
+			phi = acos(min(1.0,max(-1.0,Q/sqrt(-P))));
+			P   = 2.0*pow((-P),(5.e-1*third));
+			for(int i=0;i<3;i++)	U[i] = P*cos((phi+2*((IssmDouble)i)*pi)*third)-W;
+			x[0] = min(U[0], min(U[1], U[2]));
+			x[1] = max(min(U[0], U[1]),max( min(U[0], U[2]), min(U[1], U[2])));
+			x[2] = max(U[0], max(U[1], U[2]));
+			*num = 3;
+		}
+		else{
+			// only one real solution!
+			delta = sqrt(delta);
+			x[0] = CBRT(Q+delta)+CBRT(Q-delta)-W;
+			*num=1;
+		}
+	}
+	else if (b != 0.0){
+		// quadratic problem
+		P     = 0.5*c/b;
+		delta = pow(P,2)-d/b;
+		if (delta > 0.0){
+			// 2 real solutions
+			x[0] = -P - sqrt(delta);
+			x[1] = -P + sqrt(delta);
+			*num = 2;
+		}
+		else{
+			// no real solution
+			*num = 0;
+		}
+	}
+	else if (c != 0.0){
+		//linear equation
+		x[0] = d/c;
+		*num = 1;
+	}
+	else{
+		//no equation
+		*num = 0;
+	}
+
+	/* perform one step of a newton iteration in order to minimize round-off errors */
+	for(int i=0;i<*num;i++){
+		x[i] = x[i] - (d+x[i]*(c+x[i]*(b+x[i]*a)))/(c+x[i]*(2.0*b+x[i]*3.0*a));
+	}
+
+	return 0;
+}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 13101)
@@ -17,17 +17,18 @@
 struct OptPars;
 
-IssmDouble min(IssmDouble a,IssmDouble b);
-IssmDouble max(IssmDouble a,IssmDouble b);
-int    min(int a,int b);
-int    max(int a,int b);
-IssmDouble OptFunc(IssmDouble scalar, OptArgs* optargs);
-void   BrentSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs);
-void   OptimalSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs);
-void   cross(IssmDouble* result,IssmDouble* vector1,IssmDouble* vector2);
-void   IsInputConverged(IssmDouble* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum);
-void   UnitConversion(IssmDouble* values, int numvalues,int direction_enum, int type_enum);
-IssmDouble UnitConversion(IssmDouble value, int direction_enum, int type_enum);
-char*  OptionsFromAnalysis(Parameters* parameters,int analysis_type);
-void   XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors);
+IssmDouble  min(IssmDouble a,IssmDouble b);
+IssmDouble  max(IssmDouble a,IssmDouble b);
+int         min(int a,int b);
+int         max(int a,int b);
+IssmDouble  OptFunc(IssmDouble scalar, OptArgs *optargs);
+void        BrentSearch(IssmDouble *psearch_scalar,IssmDouble*pJ,OptPars*optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs*optargs);
+void        OptimalSearch(IssmDouble *psearch_scalar,IssmDouble*pJ,OptPars*optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs*optargs);
+void        cross(IssmDouble *result,IssmDouble*vector1,IssmDouble*vector2);
+void        IsInputConverged(IssmDouble *peps, Input**new_inputs,Input**old_inputs,int num_inputs,int criterion_enum);
+void        UnitConversion(IssmDouble *values, int numvalues,int direction_enum, int type_enum);
+IssmDouble  UnitConversion(IssmDouble value, int direction_enum, int type_enum);
+char       *OptionsFromAnalysis(Parameters *parameters,int analysis_type);
+void        XZvectorsToCoordinateSystem(IssmDouble *T,IssmDouble*xzvectors);
+int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d, double X[3], int *num);
 #ifdef _HAVE_PETSC_
 void   PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type);
Index: /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 13101)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
+	if(!pch)_error_("descriptor " << descriptor << " is not correctly formatted!");
 
 	if (strncmp(pch,"scaled",6)==0){
 		/*we have a scaled variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("scaled descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 
@@ -44,9 +44,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return IndexedEnum;
@@ -55,9 +55,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 13101)
@@ -44,10 +44,10 @@
 
 		if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
-			_error2_("pthread_create error");
+			_error_("pthread_create error");
 		}
 	}
 	for(i=0;i<num_threads;i++){
 		if(pthread_join(threads[i],(void**)&status)){
-			_error2_("pthread_join error");
+			_error_("pthread_join error");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13101)
@@ -35,5 +35,5 @@
 			break;
 		default:
-			_error2_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
+			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 13101)
@@ -110,5 +110,5 @@
 		
 		default:
-			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13101)
@@ -29,5 +29,5 @@
 			solutioncore=&diagnostic_core;
 			#else
-			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 			break;
@@ -36,5 +36,5 @@
 			solutioncore=&steadystate_core;
 			#else
-			_error2_("ISSM was not compiled with steady state capabilities. Exiting");
+			_error_("ISSM was not compiled with steady state capabilities. Exiting");
 			#endif
 			break;
@@ -43,5 +43,5 @@
 			solutioncore=&thermal_core;
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -50,5 +50,5 @@
 			solutioncore=&enthalpy_core;
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -57,5 +57,5 @@
 			solutioncore=&balancethickness_core;
 			#else
-			_error2_("ISSM was not compiled with balanced capabilities. Exiting");
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
 			#endif
 			break;
@@ -64,5 +64,5 @@
 			solutioncore=&hydrology_core;
 			#else
-			_error2_("ISSM was not compiled with hydrology capabilities. Exiting");
+			_error_("ISSM was not compiled with hydrology capabilities. Exiting");
 			#endif
 			break;
@@ -71,5 +71,5 @@
 			solutioncore=&surfaceslope_core;
 			#else
-			_error2_("ISSM was not compiled with slope capabilities. Exiting");
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -78,5 +78,5 @@
 			solutioncore=&bedslope_core;
 			#else
-			_error2_("ISSM was not compiled with slope capabilities. Exiting");
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -85,5 +85,5 @@
 			solutioncore=&transient_core;
 			#else
-			_error2_("ISSM was not compiled with transient capabilities. Exiting");
+			_error_("ISSM was not compiled with transient capabilities. Exiting");
 			#endif
 			break;
@@ -92,9 +92,9 @@
 			solutioncore=&prognostic_core;
 			#else
-			_error2_("ISSM was not compiled with prognostic capabilities. Exiting");
+			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
 			#endif
 			break;
 		default:
-			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 13101)
@@ -17,7 +17,7 @@
 	char *lockfilename   = NULL;
 
-	if(argc<2)_error2_("Usage error: no solution requested");
+	if(argc<2)_error_("Usage error: no solution requested");
 	*solution_type=StringToEnumx(argv[1]);
-	if(argc<3)_error2_("Usage error: missing model name");
+	if(argc<3)_error_("Usage error: missing model name");
 	modelname=argv[3];
 	binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 13101)
@@ -17,8 +17,8 @@
 	if(my_rank==0){
 		fid=fopen(filename,"w");
-		if(fid==NULL) _error2_("error message: could not open lock file " << filename);
+		if(fid==NULL) _error_("error message: could not open lock file " << filename);
 
 		/*Close file: */
-		if(fclose(fid)!=0) _error2_("could not close lock file " << filename);
+		if(fclose(fid)!=0) _error_("could not close lock file " << filename);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 13101)
@@ -82,5 +82,5 @@
 		/*Display info*/
 		if(VerboseControl()) _pprintLine_("\n" << "   control method step " << n+1 << "/" << nsteps);
-		for(i=0;i<num_responses;i++) step_responses[i]=(int)responses[n*num_responses+i];
+		for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
 		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
 		
@@ -99,5 +99,5 @@
 
 		if(VerboseControl()) _pprintLine_("   optimizing along gradient direction");
-		optpars.maxiter=(int)maxiter[n]; optpars.cm_jump=cm_jump[n];
+		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
 		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 13101)
@@ -13,5 +13,5 @@
 #include "../solvers/solvers.h"
 
-#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ == 2)
+#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
 #include <tao.h>
 
@@ -42,5 +42,5 @@
 	PetscGetArgs(&argc,&args);
 	ierr = TaoInitialize(&argc,&args,(char*)0,"");
-	if(ierr) _error2_("Could not initialize Tao");
+	if(ierr) _error_("Could not initialize Tao");
 
 	/*Recover some parameters*/
@@ -75,5 +75,5 @@
 	xdelete(&XU);
 
-	user.J=(double*)xcalloc((maxiter+5),sizeof(double));
+	user.J=xNewZeroInit<double>(maxiter+5);
 	user.femmodel=femmodel;
 	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
@@ -185,5 +185,5 @@
 #else
 void controltao_core(FemModel* femmodel){
-	_error2_("TAO not installed or PETSc version not supported");
+	_error_("TAO not installed or PETSc version not supported");
 }
 #endif //_HAVE_TAO_ 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 13101)
@@ -72,5 +72,5 @@
 	if (xIsNan<IssmDouble>(res)){
 		_pprintLine_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f");
-		_error2_("mechanical equilibrium convergence criterion is NaN!");
+		_error_("mechanical equilibrium convergence criterion is NaN!");
 	}
 
@@ -81,9 +81,9 @@
 	//print
 	if(res<eps_res){
-		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   mechanical equilibrium convergence criterion" << res*100 << " < " << eps_res*100 << " %");
+		if(VerboseConvergence()) _pprintLine_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<< " < "<<eps_res*100<<" %");
 		converged=true;
 	}
 	else{ 
-		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   mechanical equilibrium convergence criterion" << res*100 << " > " << eps_res*100 << " %");
+		if(VerboseConvergence()) _pprintLine_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<<" > "<<eps_res*100<<" %");
 		converged=false;
 	}
@@ -96,5 +96,5 @@
 		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
 
-		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
 
 		//clean up
@@ -121,5 +121,5 @@
 		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
 		ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
-		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
 
 		//clean up
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 13101)
@@ -20,4 +20,5 @@
 	bool  ishutter          = false;
 	bool  ismacayealpattyn  = false;
+	bool  isl1l2            = false;
 	bool  isstokes          = false;
 	bool  isnewton          = false;
@@ -33,4 +34,5 @@
 	femmodel->parameters->FindParam(&ishutter,FlowequationIshutterEnum);
 	femmodel->parameters->FindParam(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+	femmodel->parameters->FindParam(&isl1l2,FlowequationIsl1l2Enum);
 	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
 	femmodel->parameters->FindParam(&isnewton,DiagnosticIsnewtonEnum);
@@ -70,5 +72,5 @@
 	}
 
-	if (ismacayealpattyn ^ isstokes){ // ^ = xor
+	if ((ismacayealpattyn || isl1l2) ^ isstokes){ // ^ = xor
 		
 		if(VerboseSolution()) _pprintLine_("   computing velocities");
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 13101)
@@ -37,6 +37,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=new_gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*plug back into inputs: */
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 13101)
@@ -39,5 +39,5 @@
 		nsteps=1;
 	}
-	else nsteps=(int)((final_time-starttime)/dt);
+	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
 	time=starttime;
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 13101)
@@ -14,4 +14,12 @@
 	bool  dakota_analysis,control_analysis,tao_analysis;
 
+	/*AD: */
+	bool autodiff=false;
+	#if _ADOLC_VERSION_ == 2
+	int      tape_stats[11];
+	#else
+	size_t   tape_stats[11];
+	#endif
+
 	/*FemModel: */
 	FemModel *femmodel = NULL;
@@ -42,8 +50,9 @@
 	ISSMBOOT();
 
+	
 	/*Initialize environments: Petsc, MPI, etc...: */
 	#ifdef _HAVE_PETSC_
 	ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error2_("Could not initialize Petsc");
+	if(ierr) _error_("Could not initialize Petsc");
 	#else
 	#ifdef _HAVE_MPI_
@@ -100,4 +109,5 @@
 	femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
 	femmodel->parameters->FindParam(&profiling,DebugProfilingEnum); 
+	femmodel->parameters->FindParam(&autodiff,AutodiffIsautodiffEnum);
 
 	#ifdef _HAVE_MPI_
@@ -105,4 +115,9 @@
 	#else
 	finish_init=(IssmPDouble)clock();
+	#endif
+	
+	/*If running AD, then initialize the tape: */
+	#ifdef _HAVE_ADOLC_
+	if(autodiff) trace_on(1);
 	#endif
 
@@ -120,5 +135,5 @@
 		Dakotax(femmodel);
 		#else
-		_error2_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -130,5 +145,5 @@
 		 control_core(femmodel);
 		#else
-		_error2_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
+		_error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -153,4 +168,19 @@
 	_pprintLine_("write results to disk:");
 	OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+	
+	/*If running AD, close our tape, print statistics: {{{*/
+	#ifdef _HAVE_ADOLC_
+	if(autodiff){
+		trace_off();
+		tapestats(1,tape_stats); //reading of tape statistics
+		_pprintLine_("   ADOLC statistics: ");
+		_pprintLine_("   "<<setw(45)<<left<<"Number of independents: " <<tape_stats[0]);
+		_pprintLine_("   "<<setw(45)<<left<<"Number of dependents: " <<tape_stats[1]);
+		_pprintLine_("   "<<setw(45)<<left<<"Maximal number of live active variables: " <<tape_stats[2]);
+		_pprintLine_("   "<<setw(45)<<left<<"Size of value stack (number of overwrites): " <<tape_stats[3]);
+		_pprintLine_("   "<<setw(45)<<left<<"Buffer size (a multiple of eight): " <<tape_stats[4]);
+		_pprintLine_("   "<<setw(45)<<left<<"Total number of operations recorded: " <<tape_stats[5]);
+	}
+	#endif  /*}}}*/
 
 	/*Close output and petsc options file and write lock file if requested*/
@@ -200,4 +230,5 @@
 	#endif
 	#endif
+
 	
 	/*end module: */
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp	(revision 13101)
@@ -40,5 +40,5 @@
 #ifdef _HAVE_PETSC_
 	int ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error2_("Could not initialize Petsc");
+	if(ierr) _error_("Could not initialize Petsc");
 #else
 #ifdef _HAVE_MPI_
@@ -122,5 +122,5 @@
 	char *lockfilename   = NULL;
 
-	if(argc<2)_error2_("Usage error: missing model name");
+	if(argc<2)_error_("Usage error: missing model name");
 	modelname=argv[2];
 	binfilename    = xNew<char>((strlen(modelname)+strlen(".bin")   +1)); sprintf(binfilename,   "%s%s",modelname,".bin");
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp	(revision 13101)
@@ -49,5 +49,5 @@
 	}
 	else{
-		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
@@ -66,5 +66,5 @@
 	}
 	else{
-		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 13101)
@@ -52,5 +52,5 @@
 		}
 		#else
-		_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+		_error_("ISSM was not compiled with thermal capabilities. Exiting");
 		#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 13101)
@@ -104,5 +104,5 @@
 			}
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 		}
@@ -113,5 +113,5 @@
 			diagnostic_core(femmodel);
 			#else
-			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 		}
@@ -129,5 +129,5 @@
 			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
 			#else
-			_error2_("ISSM was not compiled with grounding line migration capabilities. Exiting");
+			_error_("ISSM was not compiled with grounding line migration capabilities. Exiting");
 			#endif
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp	(revision 13101)
@@ -119,5 +119,5 @@
 			break;
 		default:
-			_error2_("unknown norm !");
+			_error_("unknown norm !");
 			break;
 	}
@@ -150,6 +150,6 @@
 	AX->GetSize(&AXM);
 
-	if(M!=AXM)_error2_("A and AX should have the same number of rows!");
-	if(N!=XM)_error2_("A and X should have the same number of columns!");
+	if(M!=AXM)_error_("A and AX should have the same number of rows!");
+	if(N!=XM)_error_("A and X should have the same number of columns!");
 
 	for(i=0;i<M;i++){
@@ -197,5 +197,5 @@
 			break;
 		default:
-			_error2_("unknown insert mode!");
+			_error_("unknown insert mode!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp	(revision 13101)
@@ -85,5 +85,5 @@
 			break;
 		default:
-			_error2_("unknown insert mode!");
+			_error_("unknown insert mode!");
 			break;
 	}
@@ -102,5 +102,5 @@
 			break;
 		default:
-			_error2_("unknown insert mode!");
+			_error_("unknown insert mode!");
 			break;
 	}
@@ -204,5 +204,5 @@
 			break;
 		default:
-			_error2_("unknown norm !");
+			_error_("unknown norm !");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 13101)
@@ -60,5 +60,5 @@
 
 	#else
-	_error2_("METIS version not supported yet");
+	_error_("METIS version not supported yet");
 	#endif
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown insert mode!");
+			_error_("unknown insert mode!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown matrix type !");
+			_error_("unknown matrix type !");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13101)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown norm !");
+			_error_("unknown norm !");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 13101)
@@ -29,5 +29,5 @@
 	/*Some checks: */
 	MatGetSize(matrix,&M,&N);
-	if(M!=N) _error2_("trying to invert a non square matrix!");
+	if(M!=N) _error_("trying to invert a non square matrix!");
 
 	/*Create identitiy matrix: */
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 13101)
@@ -62,5 +62,5 @@
 		}
 		else{
-			_error2_("MatType " << type << " not supported yet");
+			_error_("MatType " << type << " not supported yet");
 		}
 		/*Assemble*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13101)
@@ -55,5 +55,5 @@
 			if(first[0]!='-'){
 				/*This is not good, the option does not have '-'! Get out*/
-				_error2_("Option " << first << " should be preceded by '-'!");
+				_error_("Option " << first << " should be preceded by '-'!");
 			}
 			/*Reduce first to bare option value*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13101)
@@ -35,5 +35,5 @@
 	/*If the dimension of the partitioning vector is not the same as that of vector B, we have a problem: */
 	if ( (row_partition_size !=MB) ){
-		_error2_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
+		_error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13101)
@@ -51,5 +51,5 @@
 
 	/*Some dimensions checks: */
-	if (mA!=nA) _error2_("trying to take the invert of a non-square matrix!");
+	if (mA!=nA) _error_("trying to take the invert of a non-square matrix!");
 
 	/* Set default Plapack parameters */
Index: /issm/branches/trunk-jpl-damage/src/m/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/Makefile.am	(revision 13101)
@@ -1,40 +1,50 @@
-bin_SCRIPTS=./classes/*.m \
-				./classes/model/*.m \
-				./classes/clusters/*.m \
-				./enum/*.m \
-				./kml/*.m \
-				./model/*.m \
-				./model/plot/*.m \
-				./model/mesh/*.m \
-				./model/display/*.m \
-				./model/parameterization/*.m \
-				./model/partition/*.m \
-				./model/solvers/*.m \
-				./qmu/*.m \
-				./utils/*.m \
-				./utils/Array/*.m \
-				./utils/BC/*.m \
-				./utils/Basins/*.m \
-				./utils/Cluster/*.m \
-				./utils/DataProcessing/*.m \
-				./utils/Ecco3/*.m \
-				./utils/Exp/*.m \
-				./utils/Exp/manipulation/*.m \
-				./utils/Exp/readwrite/*.m \
-				./utils/Geometry/*.m \
-				./utils/ImageProcessing/*.m \
-				./utils/Interp/*.m \
-				./utils/Kml/*.m \
-				./utils/LatLong/*.m \
-				./utils/Math/*.m \
-				./utils/Meca/*.m \
-				./utils/Mesh/*.m \
-				./utils/Miscellaneous/*.m \
-				./utils/Model/*.m \
-				./utils/Numerics/*.m \
-				./utils/OS/*.m \
-				./utils/Plot/*.m \
-				./utils/Shell/*.m \
-				./utils/String/*.m \
-				./utils/consistency/*.m \
-				./utils/qmu/*.m 
+#To generate list of directories
+#
+#find . -type d -exec ls -d {} \;
+
+bin_SCRIPTS= ./qmu/*.m \
+				 ./qmu/setupdesign/*.m \
+				 ./qmu/plot/*.m \
+				 ./qmu/examples/*.m \
+				 ./kml/*.m \
+				 ./enum/*.m \
+				 ./classes/*.m \
+				 ./classes/qmu/*.m \
+				 ./classes/qmu/@dakota_method/*.m \
+				 ./classes/clusters/*.m \
+				 ./classes/model/*.m \
+				 ./consistency/*.m \
+				 ./array/*.m \
+				 ./boundaryconditions/*.m \
+				 ./exp/*.m \
+				 ./exp/manipulation/*.m \
+				 ./geometry/*.m \
+				 ./interp/*.m \
+				 ./latlong/*.m \
+				 ./meca/*.m \
+				 ./mesh/*.m \
+				 ./mesh/planet/*.m \
+				 ./mesh/rifts/*.m \
+				 ./miscellaneous/*.m \
+				 ./os/*.m \
+				 ./plot/*.m \
+				 ./plot/colormaps/*.m \
+				 ./string/*.m \
+				 ./contrib/massbalance/*.m \
+				 ./contrib/ecco/*.m \
+				 ./contrib/hydrology/*.m \
+				 ./contrib/hack/*.m \
+				 ./contrib/gslib/*.m \
+				 ./contrib/uci/*.m \
+				 ./contrib/oasis/*.m \
+				 ./contrib/bamg/*.m \
+				 ./extrusion/*.m \
+				 ./inversions/*.m \
+				 ./io/*.m \
+				 ./parameterization/*.m \
+				 ./partition/*.m \
+				 ./print/*.m \
+				 ./regional/*.m \
+				 ./solve/*.m \
+				 ./solvers/*.m \
+				 ./materials/*.m
Index: /issm/branches/trunk-jpl-damage/src/m/array/allempty.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/allempty.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/allempty.m	(revision 13101)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty cell array if all array elements are empty
+%
+%  function [cout]=allempty(cin)
+%
+function [cout]=allempty(cin)
+
+if ~nargin
+    help allempty
+    return
+end
+
+for j=1:numel(cin)
+    if ~isempty(cin{j})
+        cout=cin;
+        return
+    end
+end
+cout={};
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/array/allequal.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/allequal.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/allequal.m	(revision 13101)
@@ -0,0 +1,70 @@
+%
+%  function to return an empty array if all array elements are
+%  equal to the given value, which may also be empty but not nan.
+%
+%  (note that by definition, nan is not equal to nan.  this could
+%  be changed by using isequalwithequalnans.)
+%
+%  function [aout]=allequal(ain,aval)
+%
+function [aout]=allequal(ain,aval)
+
+if ~nargin
+    help allequal
+    return
+end
+
+aout=ain;
+
+if     islogical(ain) && islogical(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=logical([]);
+
+elseif isnumeric(ain) && isnumeric(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=[];
+
+elseif ischar(ain) && ischar(aval)
+    for i=1:size(ain,1)
+        if ~strcmp(ain(i,:),aval)
+            return
+        end
+    end
+    aout='';
+
+elseif iscell(ain)
+    if     islogical(aval)
+        for i=1:numel(ain)
+            if ~islogical(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif isnumeric(aval)
+        for i=1:numel(ain)
+            if ~isnumeric(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif ischar(aval)
+        for i=1:size(ain,1)
+            if ~ischar(ain{i}) || ~strcmp(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/allnan.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/allnan.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/allnan.m	(revision 13101)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty double array if all array elements are NaN
+%
+%  function [dout]=allnan(din)
+%
+function [dout]=allnan(din)
+
+if ~nargin
+    help allnan
+    return
+end
+
+for i=1:numel(din)
+    if ~isnan(din(i))
+        dout=din;
+        return
+    end
+end
+dout=[];
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/array/any2str.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/any2str.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/any2str.m	(revision 13101)
@@ -0,0 +1,22 @@
+%
+%  function to convert anything to a string
+%
+%  function [svec]=any2str(a,alim)
+%
+function [svec]=any2str(a,alim)
+
+if ~exist('alim','var') || (numel(a) <= alim)
+    if iscell(a)
+        svec=string_cell(a);
+    else
+        if (numel(a) > 1) && ~ischar(a)
+            svec=string_vec(a);
+        else
+            svec=item2str(a);
+        end
+    end
+else
+	svec=[string_size(a) ' ''' class(a) ''''];
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/array_numel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/array_numel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/array_numel.m	(revision 13101)
@@ -0,0 +1,35 @@
+%
+%  function to find a number of elements from a list of arrays.
+%  
+%  [asize]=array_numel(varargin)
+%
+%  see array_size to check the number and shape of elements, if
+%  multiple indices will be used.
+%
+function [anum]=array_numel(varargin)
+
+anum=1;
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        inum=numel(cellstr(varargin{iarg}));
+    else
+        inum=numel(varargin{iarg});
+    end
+    
+    if ~isequal(inum,1)
+        if isequal(anum,1)
+            anum=inum;
+        else
+            if ~isequal(inum,anum)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent number of elements.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent number of elements.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/array_size.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/array_size.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/array_size.m	(revision 13101)
@@ -0,0 +1,35 @@
+%
+%  function to find an array size from a list of arrays.
+%  
+%  [asize]=array_size(varargin)
+%
+%  see array_numel to check only the number of elements, if
+%  single indices will be used.
+%
+function [asize]=array_size(varargin)
+
+asize=[1 1];
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        isize=size(cellstr(varargin{iarg}));
+    else
+        isize=size(varargin{iarg});
+    end
+    
+    if ~isequal(isize,[1 1])
+        if isequal(asize,[1 1])
+            asize=isize;
+        else
+            if ~isequal(isize,asize)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent size.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent size.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/find_string.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/find_string.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/find_string.m	(revision 13101)
@@ -0,0 +1,18 @@
+%
+%  function to find a string in a cell array
+%  (could probably be replaced by matlab strmatch)
+%  
+%  [ifound]=find_string(cells,str)
+%
+function [ifound]=find_string(cells,str)
+
+ifound=false;
+
+for i=1:numel(cells)
+    if ischar(cells{i}) && strcmp(cells{i},str)
+        ifound=i;
+        return
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/item2str.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/item2str.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/item2str.m	(revision 13101)
@@ -0,0 +1,31 @@
+%
+%  function to convert an item to a string
+%
+%  function [svec]=item2str(a)
+%
+function [svec]=item2str(a)
+
+if     islogical(a)
+    if a
+        svec='true';
+    else
+        svec='false';
+    end
+elseif ischar(a)
+    svec=['''' a ''''];
+elseif isnumeric(a)
+    svec=num2str(a);
+else
+    if ~isempty(inputname(1))
+        warning('item2str:item_unrecog',...
+            'Item ''%s'' is of unrecognized type ''%s''.',...
+            inputname(1),class(a));
+    else
+        warning('item2str:item_unrecog',...
+            'Item %d is of unrecognized type ''%s''.',...
+            1,class(a));
+    end
+    return
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/rotateticklabel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/rotateticklabel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/rotateticklabel.m	(revision 13101)
@@ -0,0 +1,69 @@
+function th=rotateticklabel(h,rot,demo)
+%ROTATETICKLABEL rotates tick labels
+%   TH=ROTATETICKLABEL(H,ROT) is the calling form where H is a handle to
+%   the axis that contains the XTickLabels that are to be rotated. ROT is
+%   an optional parameter that specifies the angle of rotation. The default
+%   angle is 90. TH is a handle to the text objects created. For long
+%   strings such as those produced by datetick, you may have to adjust the
+%   position of the axes so the labels don't get cut off.
+%
+%   Of course, GCA can be substituted for H if desired.
+%
+%   TH=ROTATETICKLABEL([],[],'demo') shows a demo figure.
+%
+%   Known deficiencies: if tick labels are raised to a power, the power
+%   will be lost after rotation.
+%
+%   See also datetick.
+
+%   Written Oct 14, 2005 by Andy Bliss
+%   Copyright 2005 by Andy Bliss
+
+%DEMO:
+if nargin==3
+    x=[now-.7 now-.3 now];
+    y=[20 35 15];
+    figure
+    plot(x,y,'.-')
+    datetick('x',0,'keepticks')
+    h=gca;
+    set(h,'position',[0.13 0.35 0.775 0.55])
+    rot=90;
+end
+
+%set the default rotation if user doesn't specify
+if nargin==1
+    rot=90;
+end
+%make sure the rotation is in the range 0:360 (brute force method)
+while rot>360
+    rot=rot-360;
+end
+while rot<0
+    rot=rot+360;
+end
+%get current tick labels
+a=get(h,'XTickLabel');
+%erase current tick labels from figure
+set(h,'XTickLabel',[]);
+%get tick label positions
+b=get(h,'XTick');
+c=get(h,'YTick');
+%make new tick labels
+%  must consider yscale (jes, 9/14/10)
+switch lower(get(h,'YScale'))
+    case 'linear'
+        if rot<180
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    case 'log'
+        if rot<180
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    otherwise
+        set(h,'XTickLabel',a);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/str2int.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/str2int.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/str2int.m	(revision 13101)
@@ -0,0 +1,46 @@
+%
+%  function to find and read the first or last positive integer
+%  in a character string.
+%
+%  function [aint]=str2int(astr,cfl)
+%
+function [aint]=str2int(astr,cfl);
+
+aint=[];
+
+if     ~exist('cfl','var') || strncmpi(cfl,'f',1)
+    i=1;
+
+    while (i <= length(astr))
+        if (astr(i) >= '0' && astr(i) <= '9')
+            aint=sscanf(astr(i:length(astr)),'%d',[1,1]);
+            return
+        else
+            i=i+1;
+        end
+	end
+
+elseif strncmpi(cfl,'l',1)
+    i=length(astr);
+    ifound=false;
+
+    while (i >= 1)
+        if     (astr(i) >= '0' && astr(i) <= '9')
+            ifound=true;
+            i=i-1;
+        elseif ~ifound
+            i=i-1;
+        else
+            aint=sscanf(astr(i+1:length(astr)),'%d',[1,1]);
+            return
+        end
+	end
+
+    if ifound
+        aint=sscanf(astr,'%d',[1,1]);
+        return
+    end
+end
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/array/string_cell.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/string_cell.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/string_cell.m	(revision 13101)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of a cell array
+%
+%  function [svec]=string_cell(a)
+%
+function [svec]=string_cell(a)
+
+if ~nargin
+    help string_cell
+    return
+end
+
+if (numel(a) == 0)
+    svec='{}';
+    return
+end
+
+%  assemble string for output
+
+svec ='{';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a{i}) ' '];
+end
+svec=[svec item2str(a{end}) '}'];
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/string_dim.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/string_dim.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/string_dim.m	(revision 13101)
@@ -0,0 +1,72 @@
+%
+%  function to return the string dimension of an array element
+%
+%  function [sdim]=string_dim(a,idim,varargin)
+%
+function [sdim]=string_dim(a,idim,varargin)
+
+if ~nargin
+    help string_dim
+    return
+end
+
+%  check for scalar
+
+if (numel(a) == 1) && (idim == 1)
+    sdim='';
+    return
+end
+
+%  check for overflow
+
+if (idim > numel(a))
+    if ~isempty(inputname(1))
+        error('Index %d exceeds number of elements in array ''%s''.',...
+            idim,inputname(1));
+    else
+        error('Index %d exceeds number of elements in array %d.',...
+            idim,1);
+    end
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-2
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            sdim =['(' num2str(idim) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+index=zeros(size(asize));
+aprod=prod(asize);
+idim =idim-1;
+
+%  calculate indices base 0 and convert to base 1
+
+%  note that ind2sub might be useful, except that it requires a list
+%  of scalars rather than a vector for output.
+
+for i=length(asize):-1:1
+    aprod=aprod/asize(i);
+    index(i)=floor(idim/aprod);
+    idim=idim-index(i)*aprod;
+end
+index=index+1;
+
+%  assemble string for output
+
+sdim ='(';
+for i=1:length(asize)-1;
+    sdim =[sdim num2str(index(i)) ','];
+end
+sdim =[sdim num2str(index(end)) ')'];
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/array/string_size.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/string_size.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/string_size.m	(revision 13101)
@@ -0,0 +1,38 @@
+%
+%  function to return the string size of an array
+%
+%  function [ssize]=string_size(a,varargin)
+%
+function [ssize]=string_size(a,varargin)
+
+if ~nargin
+    help string_size
+    return
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-1
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            ssize =['(' num2str(numel(a)) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+
+%  assemble string for output
+
+ssize ='(';
+for i=1:length(asize)-1;
+    ssize =[ssize num2str(asize(i)) 'x'];
+end
+ssize =[ssize num2str(asize(end)) ')'];
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/array/string_vec.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/string_vec.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/string_vec.m	(revision 13101)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of an vector
+%
+%  function [svec]=string_vec(a)
+%
+function [svec]=string_vec(a)
+
+if ~nargin
+    help string_vec
+    return
+end
+
+if (numel(a) == 0)
+    svec='[]';
+    return
+end
+
+%  assemble string for output
+
+svec ='[';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a(i)) ' '];
+end
+svec=[svec item2str(a(end)) ']'];
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/struc_class.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/struc_class.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/struc_class.m	(revision 13101)
@@ -0,0 +1,30 @@
+%
+%  function to find the structural fields of a specified class
+%  
+%  [sclasso]=struc_class(sclass,cstr)
+%
+function [sclasso]=struc_class(sclass,cstr)
+
+%  collect only the objects of the appropriate class
+
+if     isa(sclass,cstr)
+    if ~isempty(inputname(1))
+        sclasso.(inputname(1))=sclass;
+    else
+        sclasso.(cstr)        =sclass;
+    end
+
+elseif isstruct(sclass)
+    fnames=fieldnames(sclass);
+    for i=1:numel(fnames)
+        if isa(sclass.(fnames{i}),cstr)
+            sclasso.(fnames{i})=sclass.(fnames{i});
+        end
+    end
+end
+
+if ~exist('sclasso','var')
+    sclasso=struct([]);
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/array/struc_desc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/array/struc_desc.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/array/struc_desc.m	(revision 13101)
@@ -0,0 +1,61 @@
+%
+%  function to find the structures with the specified descriptors
+%  
+%  [sarrayo]=struc_desc(sarray,varargin)
+%
+function [sarrayo]=struc_desc(sarray,varargin)
+
+if ~isfield(sarray,'descriptor')
+    if ~isempty(inputname(1))
+        error('Field ''descriptor'' not found in array ''%s''.',inputname(1));
+    else
+        error('Field ''descriptor'' not found in array %d.',1);
+    end
+end
+
+sarrayo=struct([]);
+
+for iarg=1:nargin-1
+    if     iscell(varargin{iarg})
+        desc=        varargin{iarg};
+    elseif ischar(varargin{iarg})
+        desc=cellstr(varargin{iarg});
+    end
+    
+    for i=1:length(desc)
+        sarrayoi=struc_desci(sarray,desc{i});
+        if ~isempty(sarrayoi)
+            if isempty(sarrayo)
+                sarrayo       =sarrayoi;
+            else
+                sarrayo(end+1)=sarrayoi;
+            end
+        end
+    end
+end
+
+%  if nothing found, return whole array
+
+if isempty(sarrayo)
+    sarrayo=sarray;
+end
+
+end
+
+%
+%  function to find the structure with the specified descriptor
+%  
+function [sarrayo]=struc_desci(sarray,str)
+
+sarrayo=struct([]);
+
+for i=1:numel(sarray)
+    if strcmp(sarray(i).descriptor,str)
+        sarrayo=sarray(i);
+        return
+    end
+end
+
+warning(['String ''' str ''' not found in array ''' inputname(1) '''.']);
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13101)
@@ -0,0 +1,64 @@
+function md=SetIceSheetBC(md)
+%SETICESHEETBC - Create the boundary conditions for diagnostic and thermal models for an IceSheet with no Ice Front
+%
+%   Usage:
+%      md=SetIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet
+pos=find(md.mesh.vertexonboundary);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on neumann (Ice Front) -> none
+if (md.mesh.dimension==2)
+	md.diagnostic.icefront=zeros(0,4);
+else
+	md.diagnostic.icefront=zeros(0,6);
+end
+
+%Create zeros basal melting rate and surface mass balance if not specified
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=50*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.m	(revision 13101)
@@ -0,0 +1,95 @@
+function md=SetIceShelfBC(md,varargin)
+%SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+%
+%   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
+%   must be given in input)
+%   Dirichlet BC are used elsewhere for diagnostic
+%
+%   Usage:
+%      md=SetIceShelfBC(md,varargin)
+%
+%   Example:
+%      md=SetIceShelfBC(md);
+%      md=SetIceShelfBC(md,'Front.exp');
+%
+%   See also: SETICESHEETBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile), error(['SetIceShelfBC error message: ice front file ' icefrontfile ' not found']); end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	nodeonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+elseif nargin==1,
+	nodeonicefront=zeros(md.mesh.numberofvertices,1);
+else
+	help SetIceShelfBC
+	error('bad usage');
+end
+pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on Ice Front
+%segment on Neumann (Ice Front)
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+%Create zeros basalforcings and surfaceforcings
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	        md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+		disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13101)
@@ -0,0 +1,98 @@
+import os
+import numpy
+
+def SetIceShelfBC(md,icefrontfile=''):
+	"""
+	SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+
+	   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
+	   must be given in input)
+	   Dirichlet BC are used elsewhere for diagnostic
+
+	   Usage:
+	      md=SetIceShelfBC(md,varargin)
+
+	   Example:
+	      md=SetIceShelfBC(md);
+	      md=SetIceShelfBC(md,'Front.exp');
+
+	   See also: SETICESHEETBC, SETMARINEICESHEETBC
+	"""
+
+	#node on Dirichlet (boundary and ~icefront)
+	if icefrontfile:
+		if not os.path.exists(icefrontfile):
+			raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
+		nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
+		nodeonicefront=double(md.mesh.vertexonboundary and nodeinsideicefront)
+	else:
+		nodeonicefront=numpy.zeros(md.mesh.numberofvertices)
+
+#	pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+	pos=[i for i,(vob,noif) in enumerate(zip(md.mesh.vertexonboundary,nodeonicefront)) if vob and not noif]
+	md.diagnostic.spcvx=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvy=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvz=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvx[pos]=0
+	md.diagnostic.spcvy[pos]=0
+	md.diagnostic.spcvz[pos]=0
+	md.diagnostic.referential=float('NaN')*numpy.ones((md.mesh.numberofvertices,6))
+
+	#Dirichlet Values
+	if numpy.size(md.inversion.vx_obs)==md.mesh.numberofvertices and numpy.size(md.inversion.vy_obs)==md.mesh.numberofvertices:
+		print '      boundary conditions for diagnostic model: spc set as observed velocities'
+		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print '      boundary conditions for diagnostic model: spc set as zero'
+
+	#segment on Ice Front
+	#segment on Neumann (Ice Front)
+#	pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
+	pos=[i for i,(noif1,noif2) in enumerate(zip(nodeonicefront[md.mesh.segments[:,0].astype('int')-1],nodeonicefront[md.mesh.segments[:,1].astype('int')-1])) if noif1 or noif2]
+	if   md.mesh.dimension==2:
+		pressureload=md.mesh.segments[pos,:]
+	elif md.mesh.dimension==3:
+#		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+		pressureload_layer1=numpy.concatenate((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]),axis=1)
+		pressureload=numpy.zeros((0,5))
+		for i in xrange(1,md.mesh.numberoflayers):
+#			pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+			pressureload=numpy.concatenate((pressureload,numpy.concatenate((pressureload_layer1[:,0:3]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d),axis=1)),axis=0)
+
+	#Add water or air enum depending on the element
+#	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
+	pressureload=numpy.concatenate((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape((-1,1))),axis=1)
+
+	#plug onto model
+	md.diagnostic.icefront=pressureload
+
+	#Create zeros basalforcings and surfaceforcings
+	if numpy.all(numpy.isnan(md.surfaceforcings.precipitation)) and (md.surfaceforcings.ispdd==1):
+		md.surfaceforcings.precipitation=numpy.zeros(md.mesh.numberofvertices)
+		print '      no surfaceforcings.precipitation specified: values set as zero'
+	if numpy.all(numpy.isnan(md.surfaceforcings.mass_balance)) and (md.surfaceforcings.ispdd==0):
+		md.surfaceforcings.mass_balance=numpy.zeros(md.mesh.numberofvertices)
+		print '      no surfaceforcings.mass_balance specified: values set as zero'
+	if numpy.all(numpy.isnan(md.basalforcings.melting_rate)):
+		md.basalforcings.melting_rate=numpy.zeros(md.mesh.numberofvertices)
+		print '      no basalforcings.melting_rate specified: values set as zero'
+	if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
+		md.balancethickness.thickening_rate=numpy.zeros(md.mesh.numberofvertices)
+		print '      no balancethickness.thickening_rate specified: values set as zero'
+
+	md.prognostic.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.balancethickness.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+
+	if numpy.size(md.initialization.temperature)==md.mesh.numberofvertices:
+		md.thermal.spctemperature=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+		pos=[i for i,vos in enumerate(md.mesh.vertexonsurface) if vos]
+		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    # impose observed temperature on surface
+		if not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
+			md.basalforcings.geothermalflux=numpy.zeros(md.mesh.numberofvertices)
+	else:
+		print '      no thermal boundary conditions created: no observed temperature found'
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 13101)
@@ -0,0 +1,107 @@
+function md=SetMarineIceSheetBC(md,varargin)
+%SETICEMARINESHEETBC - Create the boundary conditions for diagnostic and thermal models for a  Marine Ice Sheet with Ice Front
+%
+%   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+%   can be given in input, or it will be deduced as onfloatingice & onboundary)
+%   Dirichlet BC are used elsewhere for diagnostic
+%
+%   Usage:
+%      md=SetMarineIceSheetBC(md,icefrontfile)
+%      md=SetMarineIceSheetBC(md)
+%
+%   Example:
+%      md=SetMarineIceSheetBC(md,'Front.exp')
+%      md=SetMarineIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	%User provided Front.exp, use it
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile)
+		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
+	end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	vertexonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+else
+	%Guess where the ice front is
+	vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+	vertexonfloatingice(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
+	vertexonicefront=double(md.mesh.vertexonboundary & vertexonfloatingice);
+end
+pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+if isempty(pos),
+	warning('SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually')
+end
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
+pos=find(md.mesh.vertexonboundary); 
+md.hydrology.spcwatercolumn(pos,1)=1;
+
+%segment on Neumann (Ice Front)
+pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+
+%Create zeros basalforcings and surfaceforcings
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50*10^-3; %50mW/m2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 13101)
@@ -7,6 +7,4 @@
 	properties (SetAccess=public) 
 		isautodiff = false;
-		forward    = true;
-		reverse    = false;
 	end
 	methods
@@ -29,12 +27,8 @@
 
 			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
-			fielddisplay(obj,'forward','forward differentiation');
-			fielddisplay(obj,'reverse','backward differentiation');
 
 		end % }}}
 		function marshall(obj,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','forward','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','reverse','format','Boolean');
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.py	(revision 13101)
@@ -1,12 +1,20 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class autodiff:
+class autodiff(object):
+	"""
+	AUTODIFF class definition
+
+	   Usage:
+	      autodiff=autodiff();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
 		self.isautodiff = False
-		self.forward    = True
-		self.reverse    = False
 
 		#set defaults
@@ -14,15 +22,21 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   automatic differentiation parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated'))
-		string="%s\n%s"%(string,fielddisplay(obj,'forward','forward differentiation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'reverse','backward differentiation'))
+		string="%s\n%s"%(string,fielddisplay(self,'isautodiff','indicates if the automatic differentiation is activated'))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 13101)
@@ -27,5 +27,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 			%Early return
-			if solution~=BalancethicknessSolutionEnum, return; end
+			if solution~=BalancethicknessSolutionEnum(), return; end
 
 			md = checkfield(md,'balancethickness.spcthickness','forcing',1);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.py	(revision 13101)
@@ -1,11 +1,22 @@
 #module imports
 from fielddisplay import fielddisplay
-class balancethickness:
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+
+class balancethickness(object):
+	"""
+	BALANCETHICKNESS class definition
+
+	   Usage:
+	      balancethickness=balancethickness();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.spcthickness = float('NaN')
-		self.thickening_rate           = float('NaN')
-		self.stabilization           = 0
+		self.spcthickness      = float('NaN')
+		self.thickening_rate   = float('NaN')
+		self.stabilization     = 0
 
 		#set defaults
@@ -13,21 +24,39 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		
 		string='   balance thickness solution parameters:' 
 		
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0: None, 1: SU, 2: MacAyeal''s artificial diffusivity, 3:DG'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization',"0: None, 1: SU, 2: MacAyeal's artificial diffusivity, 3:DG"))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Type of stabilization used
-		obj.stabilization=1
+		self.stabilization=1
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		#Early return
+		if not solution==BalancethicknessSolutionEnum():
+			return md
+
+		md = checkfield(md,'balancethickness.spcthickness','forcing',1)
+		md = checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1)
+		md = checkfield(md,'balancethickness.stabilization','size',[1],'values',[0,1,2,3])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 13101)
@@ -24,11 +24,11 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isprognostic==0),
+			if ismember(PrognosticAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isprognostic==0),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 			end
-			if ismember(BalancethicknessAnalysisEnum,analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(ThermalAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isthermal==0),
+			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 				md = checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class basalforcings:
+class basalforcings(object):
+	"""
+	BASAL FORCINGS class definition
+
+	   Usage:
+	      basalforcings=basalforcings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +24,37 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   basal forcings parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,"melting_rate","basal melting rate (positive if melting)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"melting_rate_correction","additional melting applied when the grounding line retreats"))
-		string="%s\n%s"%(string,fielddisplay(obj,"geothermalflux","geothermal heat flux [W/m^2]"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"melting_rate","basal melting rate (positive if melting)"))
+		string="%s\n%s"%(string,fielddisplay(self,"melting_rate_correction","additional melting applied when the grounding line retreats"))
+		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if PrognosticAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isprognostic):
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+
+		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','melting_rate','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 13101)
@@ -77,6 +77,11 @@
 					%Add --gen-suppressions=all to get suppression lines
 					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
-					fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+					if ismac, 
+						fprintf(fid,'mpiexec -np %i %s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
 						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+					else
+						fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+					end
 				end
 				if ~io_gather, %concatenate the output files:
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py	(revision 13101)
@@ -4,4 +4,5 @@
 import platform
 import subprocess
+from EnumToString import EnumToString
 from issmdir import *
 from pairoptions import *
@@ -73,5 +74,5 @@
 
 		#write queuing script 
-		if not 'Windows' in platform.system():
+		if 'Windows' not in platform.system():
 
 			fid=open(modelname+'.queue','w')
@@ -79,7 +80,7 @@
 			if not isvalgrind:
 				if self.interactive:
-					fid.write('mpiexec -np %i %s/issm.exe %s %s %s ' % (self.np,self.codepath,EnumToString(solution),self.executionpath,modelname))
+					fid.write('mpiexec -np %i %s/issm.exe %s %s %s ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,modelname))
 				else:
-					fid.write('mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+					fid.write('mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname))
 			elif isgprof:
 				fid.write('\n gprof %s/issm.exe gmon.out > %s.performance' % (self.codepath,modelname))
@@ -88,5 +89,5 @@
 				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
 				fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ' % \
-					(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+					(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname))
 			if not io_gather:    #concatenate the output files:
 				fid.write('\ncat %s.outbin.* > %s.outbin' % (modelname,modelname))
@@ -98,8 +99,8 @@
 			fid.write('@echo off\n')
 			if self.interactive:
-				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution),self.executionpath,modelname))
+				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,modelname))
 			else:
 				fid.write('"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog' % \
-					(self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+					(self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname))
 			fid.close()
 
@@ -115,5 +116,5 @@
 
 		#write queuing script 
-		if not 'Windows' in platform.system():
+		if 'Windows' not in platform.system():
 
 			fid=open(modelname+'.queue','w')
@@ -140,8 +141,8 @@
 			fid.write('@echo off\n')
 			if self.interactive:
-				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution),self.executionpath,modelname))
+				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,modelname))
 			else:
 				fid.write('"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog' % \
-					(self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+					(self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname))
 			fid.close()
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/constants.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/constants.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/constants.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class constants:
+class constants(object):
+	"""
+	CONSTANTS class definition
+
+	   Usage:
+	      constants=constants();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,10 +24,10 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   constants parameters:"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"g","gravitational acceleration"))
-		string="%s\n%s"%(string,fielddisplay(obj,"yts","number of seconds in a year"))
-		string="%s\n%s"%(string,fielddisplay(obj,"referencetemperature","reference temperature used in the enthalpy model"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"g","gravitational acceleration"))
+		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year"))
+		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model"))
 
 
@@ -25,17 +35,32 @@
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#acceleration due to gravity (m/s^2)
-		obj.g=9.81
+		self.g=9.81
 
 		#converstion from year to seconds
-		obj.yts=365*24*3600
+		self.yts=365*24*3600
 
 		#the reference temperature for enthalpy model (cf Aschwanden)
-		obj.referencetemperature=223.15
+		self.referencetemperature=223.15
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'constants.g','>',0,'size',[1])
+		md = checkfield(md,'constants.yts','>',0,'size',[1])
+		md = checkfield(md,'constants.referencetemperature','size',[1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','g','format','Double')
+		WriteData(fid,'object',self,'fieldname','yts','format','Double')
+		WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/debug.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/debug.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/debug.py	(revision 13101)
@@ -1,11 +1,20 @@
 #module imports
 from fielddisplay import fielddisplay
+from WriteData import *
 
-class debug:
+class debug(object):
+	"""
+	DEBUG class definition
+
+	   Usage:
+	      debug=debug();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.valgrind=False
-		self.gprof   = False
+		self.valgrind  = False
+		self.gprof     = False
+		self.profiling = False
 		
 		#set defaults
@@ -13,16 +22,21 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   debug parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,"valgrind","use Valgrind to debug (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"gprof","use gnu-profiler to find out where the time is spent"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"valgrind","use Valgrind to debug (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"gprof","use gnu-profiler to find out where the time is spent"))
+		string="%s\n%s"%(string,fielddisplay(self,'profiling','enables profiling (memory, flops, time)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','profiling','format','Boolean')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 13101)
@@ -67,6 +67,6 @@
 
 			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum,analyses), return; end
-			%if ~ismember(DiagnosticHorizAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isdiagnostic==0), return; end
+			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses), return; end
+			%if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isdiagnostic==0), return; end
 
 			md = checkfield(md,'diagnostic.spcvx','forcing',1);
@@ -76,5 +76,5 @@
 			md = checkfield(md,'diagnostic.reltol','size',[1 1]);
 			md = checkfield(md,'diagnostic.abstol','size',[1 1]);
-			md = checkfield(md,'diagnostic.isnewton','numel',1,'values',[0 1]);
+			md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0 1]);
 			md = checkfield(md,'diagnostic.stokesreconditioning','size',[1 1],'NaN',1);
 			md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1 1],'NaN',1);
@@ -102,6 +102,6 @@
 			if any(sum(isnan(md.diagnostic.referential),2)==0),
 				pos=find(sum(isnan(md.diagnostic.referential),2)==0);
-				if any(abs(dot(md.diagnostic.referential(pos,1:3)',md.diagnostic.referential(pos,4:6)'))>eps),
-					md = checkmessage(md,['Vectors in diagnostic.referential (colums 1 to 3 and 4 to 6) must be orthogonal']);
+				if any(abs(dot(md.diagnostic.referential(pos,1:3),md.diagnostic.referential(pos,4:6),2))>eps),
+					md = checkmessage(md,['Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal']);
 				end
 			end
@@ -168,8 +168,8 @@
 			%marshall ice front
 			data=obj.icefront;
-			pos=find(data(:,end)==0); data(pos,end)=AirEnum;
-			pos=find(data(:,end)==1); data(pos,end)=WaterEnum;
-			pos=find(data(:,end)==2); data(pos,end)=IceEnum;
-			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum,'format','DoubleMat','mattype',3);
+			pos=find(data(:,end)==0); data(pos,end)=AirEnum();
+			pos=find(data(:,end)==1); data(pos,end)=WaterEnum();
+			pos=find(data(:,end)==2); data(pos,end)=IceEnum();
+			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3);
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.py	(revision 13101)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
+import sys
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class diagnostic:
+class diagnostic(object):
+	"""
+	DIAGNOSTIC class definition
+
+	   Usage:
+	      diagnostic=diagnostic();
+	"""
+
 	#properties
 	def __init__(self):
@@ -29,71 +41,154 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
-		
 		
 		string='\n   Diagnostic solution parameters:'
 		string="%s\n\n%s"%(string,'      Convergence criteria:')
 			
-		string="%s\n%s"%(string,fielddisplay(obj,'restol','mechanical equilibrium residual convergence criterion'))
-		string="%s\n%s"%(string,fielddisplay(obj,'reltol','velocity relative convergence criterion, NaN -> not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'abstol','velocity absolute convergence criterion, NaN -> not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isnewton','Apply Newton''s method instead of a Picard fixed point method'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of nonlinear iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
+		string="%s\n%s"%(string,fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','velocity relative convergence criterion, NaN -> not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN -> not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"Apply Newton's method instead of a Picard fixed point method"))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
 
 		string="%s\n%s"%(string,'      boundary conditions:')
 
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvx','x-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice'))
 
 		string="%s\n%s"%(string,'      Rift options:')
-		string="%s\n%s"%(string,fielddisplay(obj,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
-		string="%s\n%s"%(string,fielddisplay(obj,'rift_penalty_lock','number of iterations before rift penalties are locked'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked'))
 
 		string="%s\n%s"%(string,'      Penalty options:')
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized'))
 
 		string="%s\n%s"%(string,'      Other:')
-		string="%s\n%s"%(string,fielddisplay(obj,'shelf_dampening','use dampening for floating ice ? Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(obj,'referential','local referential'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','additional outputs requested'))
+		string="%s\n%s"%(string,fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for Stokes model'))
+		string="%s\n%s"%(string,fielddisplay(self,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model'))
+		string="%s\n%s"%(string,fielddisplay(self,'referential','local referential'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		#maximum of non-linear iterations.
-		obj.maxiter=100
+		self.maxiter=100
 
 		#Convergence criterion: absolute, relative and residual
-		obj.restol=10**-4;
-		obj.reltol=0.01
-		obj.abstol=10
+		self.restol=10**-4
+		self.reltol=0.01
+		self.abstol=10
 
-		obj.stokesreconditioning=10**13
-		obj.shelf_dampening=0
+		self.stokesreconditioning=10**13
+		self.shelf_dampening=0
 
 		#Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#coefficient to update the viscosity between each iteration of
 		#a diagnostic according to the following formula
 		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		obj.viscosity_overshoot=0
+		self.viscosity_overshoot=0
 
 		#Stop the iterations of rift if below a threshold
-		obj.rift_penalty_threshold=0
+		self.rift_penalty_threshold=0
 
 		#in some solutions, it might be needed to stop a run when only
 		#a few constraints remain unstable. For thermal computation, this
 		#parameter is often used.
-		obj.rift_penalty_lock=10
+		self.rift_penalty_lock=10
 
-		return obj
+		return self
 	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if DiagnosticHorizAnalysisEnum() not in analyses:
+			return md
+		#if (DiagnosticHorizAnalysisEnum() not in analyses) | (solution==TransientSolutionEnum() and not md.transient.isdiagnostic):
+		#	return md
+
+		md = checkfield(md,'diagnostic.spcvx','forcing',1)
+		md = checkfield(md,'diagnostic.spcvy','forcing',1)
+		if md.mesh.dimension==3:
+			md = checkfield(md,'diagnostic.spcvz','forcing',1)
+		md = checkfield(md,'diagnostic.restol','size',[1],'>',0)
+		md = checkfield(md,'diagnostic.reltol','size',[1])
+		md = checkfield(md,'diagnostic.abstol','size',[1])
+		md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0,1])
+		md = checkfield(md,'diagnostic.stokesreconditioning','size',[1],'NaN',1)
+		md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1],'NaN',1)
+		if md.mesh.dimension==2:
+			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),4],'NaN',1)
+		else:
+			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),6],'NaN',1)
+		md = checkfield(md,'diagnostic.icefront[:,-1]','values',[0,1,2])
+		md = checkfield(md,'diagnostic.maxiter','size',[1],'>=',1)
+		md = checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices,6])
+		if not md.diagnostic.requested_outputs:
+			md = checkfield(md,'diagnostic.requested_outputs','size',[float('NaN'),1])
+
+		#singular solution
+#		if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
+		if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx)),numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)))):
+			md.checkmessage("model is not well posed (singular). You need at least one node with fixed velocity!")
+		#CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+#		if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
+		if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=6)):
+			md.checkmessage("Each line of diagnostic.referential should contain either only NaN values or no NaN values")
+		#CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+#		if any(sum(isnan(md.diagnostic.referential),2)==0),
+		if numpy.any(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)==0):
+			pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)) if item==0]
+#			numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
+#			if numpy.any(numpy.abs(numpy.inner(md.diagnostic.referential[pos,0:2],md.diagnostic.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
+#				md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+			for item in md.diagnostic.referential[pos,:]:
+				if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
+					md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+		#CHECK THAT NO rotation specified for FS Grounded ice at base
+#		if md.mesh.dimension==3 & md.flowequation.isstokes,
+		if md.mesh.dimension==3 and md.flowequation.isstokes:
+			pos=numpy.nonzero(numpy.logical_and(md.mask.vertexongroundedice,md.mesh.vertexonbed))
+			if numpy.any(numpy.logical_not(numpy.isnan(md.diagnostic.referential[pos,:]))):
+				md.checkmessage("no referential should be specified for basal vertices of grounded ice")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcvx','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','spcvy','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','spcvz','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','restol','format','Double')
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'fieldname','abstol','format','Double')
+		WriteData(fid,'object',self,'fieldname','isnewton','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','stokesreconditioning','format','Double')
+		WriteData(fid,'object',self,'fieldname','viscosity_overshoot','format','Double')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','shelf_dampening','format','Integer')
+		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','rift_penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','rift_penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'fieldname','referential','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+
+		#marshall ice front
+		data=self.icefront
+		data[[i for i,item in enumerate(data[:,-1]) if item==0],-1]=AirEnum()
+		data[[i for i,item in enumerate(data[:,-1]) if item==1],-1]=WaterEnum()
+		data[[i for i,item in enumerate(data[:,-1]) if item==2],-1]=IceEnum()
+		WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m	(revision 13101)
@@ -35,5 +35,5 @@
 
 			%Early return
-			if solution~=FlaimSolutionEnum, return; end
+			if solution~=FlaimSolutionEnum(), return; end
 
 			md = checkfield(md,'flaim.tracks','file',1);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flaim.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flaim.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flaim.py	(revision 13101)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class flaim:
+class flaim(object):
+	"""
+	FLAIM class definition
+
+	   Usage:
+	      flaim=flaim();
+	"""
+
 	#properties
 	def __init__(self):
@@ -20,31 +31,47 @@
 		self.opt_niter          = 30000
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Displa
 		string='   FLAIM - Flight Line Adaptation using Ice sheet Modeling:'
 
 		string="%s\n\n%s"%(string,'      Input:')
-		string="%s\n%s"%(string,fielddisplay(obj,'targets'            ,'name of kml output targets file '))
-		string="%s\n%s"%(string,fielddisplay(obj,'tracks'             ,'name of kml input tracks file '))
-		string="%s\n%s"%(string,fielddisplay(obj,'flightreqs'         ,'structure of kml flight requirements (not used yet)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)'))
+		string="%s\n%s"%(string,fielddisplay(self,'targets'            ,'name of kml output targets file '))
+		string="%s\n%s"%(string,fielddisplay(self,'tracks'             ,'name of kml input tracks file '))
+		string="%s\n%s"%(string,fielddisplay(self,'flightreqs'         ,'structure of kml flight requirements (not used yet)'))
+		string="%s\n%s"%(string,fielddisplay(self,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)'))
 
 		string="%s\n\n%s"%(string,'      Arguments:')
-		string="%s\n%s"%(string,fielddisplay(obj,'gridsatequator'     ,'number of grids at equator (determines resolution)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'usevalueordering'   ,'flag to consider target values for flight path evaluation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'split_antimeridian' ,'flag to split polygons on the antimeridian'))
+		string="%s\n%s"%(string,fielddisplay(self,'gridsatequator'     ,'number of grids at equator (determines resolution)'))
+		string="%s\n%s"%(string,fielddisplay(self,'usevalueordering'   ,'flag to consider target values for flight path evaluation'))
+		string="%s\n%s"%(string,fielddisplay(self,'split_antimeridian' ,'flag to split polygons on the antimeridian'))
 		
 		string="%s\n\n%s"%(string,'      Optimization:')
-		string="%s\n%s"%(string,fielddisplay(obj,'path_optimize'     ,'optimize? (default false)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_ndir'     ,['number of directions to test when moving a point.  If this value = 1, a random direction is tested.',\
+		string="%s\n%s"%(string,fielddisplay(self,'path_optimize'     ,'optimize? (default false)'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_ndir'     ,['number of directions to test when moving a point.  If this value = 1, a random direction is tested.',\
 										  'A value > 1 results in directions equally spaced from [0, 2*PI] being tested.',\
 										  'For example, 4 would result in directions [0, PI/2, PI, 3PI/2].']))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration'))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_niter'     ,['number of iterations (default 30,000) to run for flightplan optimization',\
+		string="%s\n%s"%(string,fielddisplay(self,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_niter'     ,['number of iterations (default 30,000) to run for flightplan optimization',\
 										   'i.e. the number of times to randomly select a point and move it.']))
 
 		string="%s\n\n%s"%(string,'      Output:')
-		string="%s\n%s"%(string,fielddisplay(obj,'solution'           ,'name of kml solution file'))
-		string="%s\n%s"%(string,fielddisplay(obj,'quality'            ,'quality of kml solution'))
+		string="%s\n%s"%(string,fielddisplay(self,'solution'           ,'name of kml solution file'))
+		string="%s\n%s"%(string,fielddisplay(self,'quality'            ,'quality of kml solution'))
 		return string
 		#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==FlaimSolutionEnum():
+			return md
+
+		md = checkfield(md,'flaim.tracks','file',1)
+		if numpy.any(numpy.isnan(md.flaim.criterion)) or not md.flaim.criterion:
+			md = checkfield(md,'flaim.targets','file',1)
+		else:
+			md = checkfield(md,'flaim.criterion','numel',[md.mesh.numberofvertices,md.mesh.numberofelements])
+
+		return md
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 13101)
@@ -8,4 +8,5 @@
 		ismacayealpattyn     = 0;
 		ishutter             = 0;
+		isl1l2               = 0;
 		isstokes             = 0;
 		vertex_equation      = NaN;
@@ -29,9 +30,10 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(DiagnosticHorizAnalysisEnum,analyses),
+			if ismember(DiagnosticHorizAnalysisEnum(),analyses),
 
-				md = checkfield(md,'flowequation.ismacayealpattyn','numel',1,'values',[0 1]);
-				md = checkfield(md,'flowequation.ishutter','numel',1,'values',[0 1]);
-				md = checkfield(md,'flowequation.isstokes','numel',1,'values',[0 1]);
+				md = checkfield(md,'flowequation.ismacayealpattyn','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.ishutter','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isl1l2','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0 1]);
 				md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
@@ -41,14 +43,14 @@
 					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
 				else
-					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:7]);
-					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:7]);
+					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
+					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
 				end
-				if (md.flowequation.ismacayealpattyn==0 && md.flowequation.ishutter==0 && md.flowequation.isstokes==0),
+				if ~(obj.ismacayealpattyn || obj.ishutter || obj.isstokes || obj.isl1l2),
 					md = checkmessage(md,['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
 				end
 			end
-			if ismember(DiagnosticHutterAnalysisEnum,analyses),
-				if any(md.flowequation.element_equation==1),
-					if(md.flowequation.element_equation & md.mask.elementonfloatingice),
+			if ismember(DiagnosticHutterAnalysisEnum(),analyses),
+				if any(obj.element_equation==1),
+					if(obj.element_equation & md.mask.elementonfloatingice),
 						disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
 					end
@@ -62,4 +64,5 @@
 			fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?');
 			fielddisplay(obj,'ishutter','is the shallow ice approximation used ?');
+			fielddisplay(obj,'isl1l2','is the l1l2 approximation used ?');
 			fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?');
 			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
@@ -73,4 +76,5 @@
 			WriteData(fid,'object',obj,'fieldname','ismacayealpattyn','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','ishutter','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isl1l2','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','isstokes','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','bordermacayeal','format','DoubleMat','mattype',1);
@@ -79,23 +83,25 @@
 			%convert approximations to enums
 			data=obj.vertex_equation;
-			pos=find(data==0); data(pos,end)=NoneApproximationEnum;
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum;
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
-			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum,'format','DoubleMat','mattype',1);
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
 			data=obj.element_equation;
-			pos=find(data==0); data(pos,end)=NoneApproximationEnum;
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum;
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
-			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum,'format','DoubleMat','mattype',2);
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2);
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.py	(revision 13101)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class flowequation:
+class flowequation(object):
+	"""
+	FLOWEQUATION class definition
+
+	   Usage:
+	      flowequation=flowequation();
+	"""
+
 	#properties
 	def __init__(self):
@@ -9,4 +20,5 @@
 		self.ismacayealpattyn     = 0;
 		self.ishutter             = 0;
+		self.isl1l2             = 0;
 		self.isstokes             = 0;
 		self.vertex_equation      = float('NaN')
@@ -20,22 +32,83 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   flow equation parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'ishutter','is the shallow ice approximation used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vertex_equation','flow equation for each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'element_equation','flow equation for each element'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bordermacayeal','vertices on MacAyeal''s border (for tiling)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'borderpattyn','vertices on Pattyn''s border (for tiling)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'borderstokes','vertices on Stokes'' border (for tiling)'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'ismacayealpattyn','is the macayeal or pattyn approximation used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'ishutter','is the shallow ice approximation used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'isl1l2','are l1l2 equations used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'isstokes','are the Full-Stokes equations used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_equation','flow equation for each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'element_equation','flow equation for each element'))
+		string="%s\n%s"%(string,fielddisplay(self,'bordermacayeal','vertices on MacAyeal''s border (for tiling)'))
+		string="%s\n%s"%(string,fielddisplay(self,'borderpattyn','vertices on Pattyn''s border (for tiling)'))
+		string="%s\n%s"%(string,fielddisplay(self,'borderstokes','vertices on Stokes'' border (for tiling)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if DiagnosticHorizAnalysisEnum() in analyses:
+			md = checkfield(md,'flowequation.ismacayealpattyn','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.ishutter','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isl1l2','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices],'values',[0,1])
+			if md.mesh.dimension==2:
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
+			else:
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',range(0,7+1))
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',range(0,7+1))
+			if not (self.ismacayealpattyn or self.ishutter or self.isstokes or self.isl1l2):
+				md.checkmessage("no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1")
+
+		if DiagnosticHutterAnalysisEnum() in analyses:
+			if any(self.element_equation==1):
+				if numpy.any(numpy.logical_and(self.element_equation,md.mask.elementonfloatingice)):
+					print "\n !!! Warning: Hutter's model is not consistent on ice shelves !!!\n"
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','ismacayealpattyn','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','ishutter','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isl1l2','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isstokes','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','bordermacayeal','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderpattyn','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderstokes','format','DoubleMat','mattype',1)
+		#convert approximations to enums
+		data=self.vertex_equation
+		data[[i for i,item in enumerate(data) if item==0]]=NoneApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==1]]=HutterApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==2]]=MacAyealApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==3]]=PattynApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==4]]=StokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==5]]=MacAyealPattynApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==6]]=MacAyealStokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==7]]=PattynStokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==8]]=L1L2ApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
+		data=self.element_equation
+		data[[i for i,item in enumerate(data) if item==0]]=NoneApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==1]]=HutterApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==2]]=MacAyealApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==3]]=PattynApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==4]]=StokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==5]]=MacAyealPattynApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==6]]=MacAyealStokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==7]]=PattynStokesApproximationEnum()
+		data[[i for i,item in enumerate(data) if item==8]]=L1L2ApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/friction.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/friction.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/friction.m	(revision 13101)
@@ -25,5 +25,5 @@
 
 			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum,analyses) & ~ismember(ThermalAnalysisEnum,analyses), return; end
+			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
 
 			md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/friction.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/friction.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/friction.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class friction:
+class friction(object):
+	"""
+	FRICTION class definition
+
+	   Usage:
+	      friction=friction();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +24,35 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"coefficient","friction coefficient [SI]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"p","p exponent"))
-		string="%s\n%s"%(string,fielddisplay(obj,"q","q exponent"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
+		string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
 		return string
 		#}}}
 
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if DiagnosticHorizAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'friction.q','NaN',1,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'friction.p','NaN',1,'size',[md.mesh.numberofelements])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m	(revision 13101)
@@ -32,5 +32,5 @@
 				md = checkmessage(md,['equality thickness=surface-bed violated']);
 			end 
-			if solution==TransientSolutionEnum & md.transient.isgroundingline,
+			if solution==TransientSolutionEnum() & md.transient.isgroundingline,
 				md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
@@ -47,8 +47,8 @@
 		end % }}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum);
-			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum);
-			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum);
-			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum);
+			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
+			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum());
+			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
+			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum());
 			WriteData(fid,'object',obj,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/geometry.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/geometry.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/geometry.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class geometry:
+class geometry(object):
+	"""
+	GEOMETRY class definition
+
+	   Usage:
+	      geometry=geometry();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,20 +26,41 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
 		string="   geometry parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'surface','surface elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickness','ice thickness'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bed','bed elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bathymetry','bathymetry elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'surface','surface elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness','ice thickness'))
+		string="%s\n%s"%(string,fielddisplay(self,'bed','bed elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'bathymetry','bathymetry elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0)
+		if any((self.thickness-self.surface+self.bed)>10**-9):
+			md.checkmessage("equality thickness=surface-bed violated")
+		if solution==TransientSolutionEnum() and md.transient.isgroundingline:
+			md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
+		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum())
+		WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
+		WriteData(fid,'data',self.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum())
+		WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 13101)
@@ -36,11 +36,11 @@
 					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
 				end
-				pos=find(md.mask.vertexongroundedice); 
+				pos=find(md.mask.vertexongroundedice);
 				if any(abs(md.geometry.bed(pos)-md.geometry.bathymetry(pos))>10^-10),
-					md = checkmessage(md,['bathymetry not equal to bed on grounded ice !']);
+					md = checkmessage(md,['bathymetry not equal to bed on grounded ice!']);
 				end
-				pos=find(md.mask.vertexonfloatingice); 
+				pos=find(md.mask.vertexonfloatingice);
 				if any(md.geometry.bathymetry(pos)-md.geometry.bed(pos)>10^-9),
-					md = checkmessage(md,['bathymetry superior to bed on floating ice !']);
+					md = checkmessage(md,['bathymetry superior to bed on floating ice!']);
 				end
 			end
@@ -55,5 +55,5 @@
 		end % }}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum,'format','Integer');
+			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
 			WriteData(fid,'object',obj,'fieldname','melting_rate','format','Double');
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.py	(revision 13101)
@@ -1,6 +1,19 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+from MatlabFuncs import *
 
-class groundingline:
+class groundingline(object):
+	"""
+	CONSTANTS class definition
+
+	   Usage:
+	      groundingline=groundingline();
+	"""
+
 	#properties
 	def __init__(self):
@@ -13,22 +26,44 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   grounding line solution parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
-		string="%s\n%s"%(string,fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
+		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating'))
 		return string
 		#}}}	
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 
 		#Type of migration
-		obj.migration='None'
+		self.migration='None'
 
 		#basal melting rate correction: 
-		obj.melting_rate=0;
+		self.melting_rate=0;
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'groundingline.migration','values',['None','AgressiveMigration','SoftMigration'])
+
+		if not strcmp(self.migration,'None'):
+			if numpy.any(numpy.isnan(md.geometry.bathymetry)):
+				md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
+			pos=numpy.nonzero(md.mask.vertexongroundedice)
+			if any(numpy.abs(md.geometry.bed[pos]-md.geometry.bathymetry[pos])>10**-10):
+				md.checkmessage("bathymetry not equal to bed on grounded ice!")
+			pos=numpy.nonzero(md.mask.vertexonfloatingice)
+			if any(md.geometry.bathymetry[pos]-md.geometry.bed[pos]>10**-9):
+				md.checkmessage("bathymetry superior to bed on floating ice!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
+		WriteData(fid,'object',self,'fieldname','melting_rate','format','Double')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 13101)
@@ -38,5 +38,5 @@
 
 			%Early return
-			if ~ismember(HydrologyAnalysisEnum,analyses), return; end
+			if ~ismember(HydrologyAnalysisEnum(),analyses), return; end
 
 			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
@@ -57,5 +57,5 @@
 		function marshall(obj,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','n','format','Double'); 
+			WriteData(fid,'object',obj,'fieldname','n','format','Double');
 			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
 			WriteData(fid,'object',obj,'fieldname','p','format','Double');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class hydrology:
+class hydrology(object):
+	"""
+	HYDROLOGY class definition
+
+	   Usage:
+	      hydrology=hydrology();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,34 +27,55 @@
 		self.setdefaultparameters()
 
-	
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		
 		string='   hydrology solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'n','Manning roughness coefficient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'CR','tortuosity parameter'))
-		string="%s\n%s"%(string,fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'kn','parameter in effective pressure formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'n','Manning roughness coefficient'))
+		string="%s\n%s"%(string,fielddisplay(self,'CR','tortuosity parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'p','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'q','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'kn','parameter in effective pressure formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Parameters from Johnson's 2002 thesis, section 3.5.4			 
-		obj.n=.02			
-		obj.CR=.01
-		obj.p=2
-		obj.q=1
-		obj.kn=0
+		self.n=.02			
+		self.CR=.01
+		self.p=2
+		self.q=1
+		self.kn=0
 
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
-		obj.stabilization=1
+		self.stabilization=1
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if HydrologyAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'hydrology.spcwatercolumn','forcing',1)
+		md = checkfield(md,'hydrology.stabilization','>=',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','n','format','Double')
+		WriteData(fid,'object',self,'fieldname','CR','format','Double')
+		WriteData(fid,'object',self,'fieldname','p','format','Double')
+		WriteData(fid,'object',self,'fieldname','q','format','Double')
+		WriteData(fid,'object',self,'fieldname','kn','format','Double')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m	(revision 13101)
@@ -30,18 +30,18 @@
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			if ismember(DiagnosticHorizAnalysisEnum,analyses)
-				if ~isnan(md.initialization.vx) & ~isnan(md.initialization.vy),
+			if ismember(DiagnosticHorizAnalysisEnum(),analyses)
+				if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
 					md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 					md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				end
 			end
-			if ismember(PrognosticAnalysisEnum,analyses),
+			if ismember(PrognosticAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(HydrologyAnalysisEnum,analyses),
+			if ismember(HydrologyAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(BalancethicknessAnalysisEnum,analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -51,5 +51,5 @@
 				end
 			end
-			if ismember(ThermalAnalysisEnum,analyses),
+			if ismember(ThermalAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -57,5 +57,5 @@
 				md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum,
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum(),
 				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/initialization.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/initialization.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/initialization.py	(revision 13101)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class initialization:
+class initialization(object):
+	"""
+	INITIALIZATION class definition
+
+	   Usage:
+	      initialization=initialization();
+	"""
+
 	#properties
 	def __init__(self):
@@ -20,23 +31,61 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   initial field values:'
 
-		string="%s\n%s"%(string,fielddisplay(obj,'vx','x component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vy','y component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vz','z component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vel','velocity norm'))
-		string="%s\n%s"%(string,fielddisplay(obj,'pressure','pressure field'))
-		string="%s\n%s"%(string,fielddisplay(obj,'temperature','temperature in Kelvins'))
-		string="%s\n%s"%(string,fielddisplay(obj,'watercolumn','thickness of subglacial water'))
-		string="%s\n%s"%(string,fielddisplay(obj,'waterfraction','fraction of water in the ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vz','z component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel','velocity norm'))
+		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure field'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature in Kelvins'))
+		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water'))
+		string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if DiagnosticHorizAnalysisEnum() in analyses:
+			if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
+				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if PrognosticAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if HydrologyAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			#Triangle with zero velocity
+			if numpy.any(numpy.logical_and(numpy.sum(numpy.abs(md.initialization.vx[md.mesh.elements.astype(int)-1]),axis=1)==0,\
+			                               numpy.sum(numpy.abs(md.initialization.vy[md.mesh.elements.astype(int)-1]),axis=1)==0)):
+				md.checkmessage("at least one triangle has all its vertices with a zero velocity")
+		if ThermalAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices])
+		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy) or solution==EnthalpySolutionEnum():
+			md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum())
+		WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum())
+		WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum())
+		WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
+		WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
+		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
+		WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m	(revision 13101)
@@ -1,3 +1,3 @@
-%CONSTANTS class definition
+%INVERSION class definition
 %
 %   Usage:
@@ -97,5 +97,5 @@
 			checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
 
-			if solution==BalancethicknessSolutionEnum
+			if solution==BalancethicknessSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			else
@@ -159,21 +159,23 @@
 				data(i)=StringToEnum(obj.control_parameters{i});
 			end
-			WriteData(fid,'data',data,'enum',InversionControlParametersEnum,'format','DoubleMat','mattype',3);
-			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum,'format','Integer');
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
 
 			%process cost functions
 			num_cost_functions=size(obj.cost_functions,2);
 			data=obj.cost_functions;
-			pos=find(data==101); data(pos)=SurfaceAbsVelMisfitEnum;
-			pos=find(data==102); data(pos)=SurfaceRelVelMisfitEnum;
-			pos=find(data==103); data(pos)=SurfaceLogVelMisfitEnum;
-			pos=find(data==104); data(pos)=SurfaceLogVxVyMisfitEnum;
-			pos=find(data==105); data(pos)=SurfaceAverageVelMisfitEnum;
-			pos=find(data==201); data(pos)=ThicknessAbsMisfitEnum;
-			pos=find(data==501); data(pos)=DragCoefficientAbsGradientEnum;
-			pos=find(data==502); data(pos)=RheologyBbarAbsGradientEnum;
-			pos=find(data==503); data(pos)=ThicknessAbsGradientEnum;
-			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum,'format','DoubleMat','mattype',3);
-			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum,'format','Integer');
+			pos=find(data==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(data==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(data==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(data==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(data==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(data==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(data==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(data==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(data==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(data==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(data==505); data(pos)=ThicknessAcrossGradientEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/inversion.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/inversion.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/inversion.py	(revision 13101)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
 
-class inversion:
+class inversion(object):
+	"""
+	INVERSION class definition
+
+	   Usage:
+	      inversion=inversion();
+	"""
+
 	#properties
 	def __init__(self):
@@ -25,25 +37,29 @@
 		self.vel_obs                     = float('NaN')
 		self.thickness_obs               = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='\n   Inversion parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'iscontrol','is inversion activated?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'incomplete_adjoint','do we assume linear viscosity?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
-		string="%s\n%s"%(string,fielddisplay(obj,'nsteps','number of optimization searches'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter_per_step','maximum iterations during each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'step_threshold','decrease threshold for misfit, default is 30%'))
-		string="%s\n%s"%(string,fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'gradient_only','stop control method solution at gradient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vx_obs','observed velocity x component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vy_obs','observed velocity y component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vel_obs','observed velocity magnitude [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickness_obs','observed thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'iscontrol','is inversion activated?'))
+		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','do we assume linear viscosity?'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
+		string="%s\n%s"%(string,fielddisplay(self,'nsteps','number of optimization searches'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter_per_step','maximum iterations during each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'step_threshold','decrease threshold for misfit, default is 30%'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'gradient_only','stop control method solution at gradient'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
 		string="%s\n%s"%(string,'Available cost functions:')
 		string="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit')
@@ -59,20 +75,19 @@
 		#}}}
 
-	def setdefaultparameters(obj):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#default is incomplete adjoint for now
-		obj.incomplete_adjoint=1
+		self.incomplete_adjoint=1
 
 		#parameter to be inferred by control methods (only
 		#drag and B are supported yet)
-		obj.control_parameters=['FrictionCoefficient']
+		self.control_parameters='FrictionCoefficient'
 
 		#number of steps in the control methods
-		obj.nsteps=20
+		self.nsteps=20
 
 		#maximum number of iteration in the optimization algorithm for
 		#each step
-		obj.maxiter_per_step=20*ones(obj.nsteps)
+		self.maxiter_per_step=20*numpy.ones(self.nsteps)
 
 		#the inversed parameter is updated as follows:
@@ -81,24 +96,100 @@
 		#inversed parameter (10^8 for B, 50 for drag) and can be decreased
 		#after the first iterations
-		obj.gradient_scaling=50*ones(obj.nsteps)
+		self.gradient_scaling=50*numpy.ones(self.nsteps)
 
 		#several responses can be used:
-		obj.cost_functions=101*ones(obj.nsteps)
+		self.cost_functions=101*numpy.ones(self.nsteps)
 
 		#step_threshold is used to speed up control method. When
-		#misfit(1)/misfit(0) < obj.step_threshold, we go directly to
+		#misfit(1)/misfit(0) < self.step_threshold, we go directly to
 		#the next step
-		obj.step_threshold=.7*ones(obj.nsteps) #30 per cent decrement
+		self.step_threshold=.7*numpy.ones(self.nsteps) #30 per cent decrement
 
 		#stop control solution at the gradient computation and return it? 
-		obj.gradient_only=0
+		self.gradient_only=0
 
 		#cost_function_threshold is a criteria to stop the control methods.
 		#if J[n]-J[n-1]/J[n] < criteria, the control run stops
 		#NaN if not applied
-		obj.cost_function_threshold=NaN #not activated 
+		self.cost_function_threshold=float('NaN')    #not activated 
 
-		return obj
-		#}}}
+		return self
+	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
 
+		#Early return
+		if not self.iscontrol:
+			return md
+
+		num_controls=numpy.size(md.inversion.control_parameters)
+		num_costfunc=numpy.size(md.inversion.cost_functions,1)
+
+		md = checkfield(md,'inversion.iscontrol','values',[0,1])
+		md = checkfield(md,'inversion.tao','values',[0,1])
+		md = checkfield(md,'inversion.incomplete_adjoint','values',[0,1])
+		md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','Vx','Vy'])
+		md = checkfield(md,'inversion.nsteps','numel',[1],'>=',1)
+		md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
+		md = checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps])
+		md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps,num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
+		md = checkfield(md,'inversion.gradient_only','values',[0,1])
+		md = checkfield(md,'inversion.gradient_scaling','size',[md.inversion.nsteps,num_controls])
+		md = checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
+		md = checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
+
+		if solution==BalancethicknessSolutionEnum():
+			md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1)
+		else:
+			md = checkfield(md,'inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1)
+			md = checkfield(md,'inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','tao','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean')
+		if not self.iscontrol:
+			return
+		WriteData(fid,'object',self,'fieldname','nsteps','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_function_threshold','format','Double')
+		WriteData(fid,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','gradient_only','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
+
+		#process control parameters
+		num_control_parameters=numpy.size(self.control_parameters)
+		data=[StringToEnum(self.control_parameters[i])[0] for i in xrange(0,num_control_parameters)]
+		WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
+
+		#process cost functions
+		num_cost_functions=size(self.cost_functions,1)
+		data=self.cost_functions
+		data[[i for i,item in enumerate(data) if item==101]]=SurfaceAbsVelMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==102]]=SurfaceRelVelMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==103]]=SurfaceLogVelMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==104]]=SurfaceLogVxVyMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==105]]=SurfaceAverageVelMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==201]]=ThicknessAbsMisfitEnum()
+		data[[i for i,item in enumerate(data) if item==501]]=DragCoefficientAbsGradientEnum()
+		data[[i for i,item in enumerate(data) if item==502]]=RheologyBbarAbsGradientEnum()
+		data[[i for i,item in enumerate(data) if item==503]]=ThicknessAbsGradientEnum()
+		data[[i for i,item in enumerate(data) if item==504]]=ThicknessAlongGradientEnum()
+		data[[i for i,item in enumerate(data) if item==505]]=ThicknessAcrossGradientEnum()
+		WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/mask.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/mask.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/mask.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class mask:
+class mask(object):
+	"""
+	MASK class definition
+
+	   Usage:
+	      mask=mask();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,20 +27,41 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
 		string="";
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonfloatingice","element on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonfloatingice","vertex on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementongroundedice","element on grounded ice  list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexongroundedice","vertex on grounded ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonwater","element on water flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonwater","vertex on water flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonfloatingice","element on floating ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonfloatingice","vertex on floating ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementongroundedice","element on grounded ice  list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexongroundedice","vertex on grounded ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonwater","element on water flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonwater","vertex on water flags list"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.vertexonfloatingice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mask.vertexongroundedice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mask.vertexonwater'       ,'size',[md.mesh.numberofvertices],'values',[0,1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','elementonfloatingice','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','elementongroundedice','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','elementonwater','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','vertexonfloatingice','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vertexongroundedice','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vertexonwater','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/materials.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/materials.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/materials.m	(revision 13101)
@@ -6,15 +6,15 @@
 classdef materials
 	properties (SetAccess=public) 
-		rho_ice                    = 0;
-		rho_water                  = 0;
-		rho_freshwater             = 0;
-		mu_water                   = 0;
-		heatcapacity               = 0;
-		latentheat                 = 0;
-		thermalconductivity        = 0;
-		meltingpoint               = 0;
-		beta                       = 0;
-		mixed_layer_capacity       = 0;
-		thermal_exchange_velocity  = 0;
+		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;
@@ -34,11 +34,11 @@
 
 			%ice density (kg/m^3)
-			obj.rho_ice=917;
+			obj.rho_ice=917.;
 
 			%ocean water density (kg/m^3)
-			obj.rho_water=1023;
+			obj.rho_water=1023.;
 
 			%fresh water density (kg/m^3)
-			obj.rho_freshwater=1000;
+			obj.rho_freshwater=1000.;
 
 			%water viscosity (N.s/m^2)
@@ -46,5 +46,5 @@
 
 			%ice heat capacity cp (J/kg/K)
-			obj.heatcapacity=2093;
+			obj.heatcapacity=2093.;
 
 			%ice latent heat of fusion L (J/kg)
@@ -61,5 +61,5 @@
 
 			%mixed layer (ice-water interface) heat capacity (J/kg/K)
-			obj.mixed_layer_capacity=3974;
+			obj.mixed_layer_capacity=3974.;
 
 			%thermal exchange velocity (ice-water interface) (m/s)
@@ -114,5 +114,5 @@
 			WriteData(fid,'object',obj,'fieldname','rheology_n','format','DoubleMat','mattype',2);
 			WriteData(fid,'object',obj,'fieldname','rheology_Z','format','DoubleMat','mattype',1);
-			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum,'format','Integer');
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/materials.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/materials.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/materials.py	(revision 13101)
@@ -1,80 +1,125 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
 
-class materials:
+class materials(object):
+	"""
+	MATERIALS class definition
+
+	   Usage:
+	      materials=materials();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.rho_ice                    = 0;
-		self.rho_water                  = 0;
-		self.mu_water                   = 0;
-		self.heatcapacity               = 0;
-		self.latentheat                 = 0;
-		self.thermalconductivity        = 0;
-		self.meltingpoint               = 0;
-		self.beta                       = 0;
-		self.mixed_layer_capacity       = 0;
-		self.thermal_exchange_velocity  = 0;
+		self.rho_ice                    = 0.
+		self.rho_water                  = 0.
+		self.rho_freshwater             = 0.
+		self.mu_water                   = 0.
+		self.heatcapacity               = 0.
+		self.latentheat                 = 0.
+		self.thermalconductivity        = 0.
+		self.meltingpoint               = 0.
+		self.beta                       = 0.
+		self.mixed_layer_capacity       = 0.
+		self.thermal_exchange_velocity  = 0.
 		self.rheology_B   = float('NaN')
 		self.rheology_n   = float('NaN')
-		self.rheology_law = "";
+		self.rheology_law = ''
 
 		self.setdefaultparameters()
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   Materials:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,"rho_ice","ice density [kg/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rho_water","water density [kg/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"mu_water","water viscosity [N s/m^2]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"heatcapacity","heat capacity [J/kg/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"thermalconductivity","ice thermal conductivity [W/m/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"meltingpoint","melting point of ice at 1atm in K"))
-		string="%s\n%s"%(string,fielddisplay(obj,"latentheat","latent heat of fusion [J/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"beta","rate of change of melting point with pressure [K/Pa]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_n","Glen""s flow law exponent"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_law","law for the temperature dependance of the rheology: ""None"", ""Paterson"" or ""Arrhenius"""))
+		string="%s\n\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+		string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson' or 'Arrhenius'"))
 
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		#ice density (kg/m^3)
-		obj.rho_ice=917
+		self.rho_ice=917.
 
-		#water density (kg/m^3)
-		obj.rho_water=1023
+		#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)
-		obj.mu_water=0.001787  
+		self.mu_water=0.001787  
 
 		#ice heat capacity cp (J/kg/K)
-		obj.heatcapacity=2093
+		self.heatcapacity=2093.
 
 		#ice latent heat of fusion L (J/kg)
-		obj.latentheat=3.34*10**5
+		self.latentheat=3.34*10**5
 
 		#ice thermal conductivity (W/m/K)
-		obj.thermalconductivity=2.4
+		self.thermalconductivity=2.4
 
 		#the melting point of ice at 1 atmosphere of pressure in K
-		obj.meltingpoint=273.15
+		self.meltingpoint=273.15
 
 		#rate of change of melting point with pressure (K/Pa)
-		obj.beta=9.8*10**-8
+		self.beta=9.8*10**-8
 
 		#mixed layer (ice-water interface) heat capacity (J/kg/K)
-		obj.mixed_layer_capacity=3974
+		self.mixed_layer_capacity=3974.
 
 		#thermal exchange velocity (ice-water interface) (m/s)
-		obj.thermal_exchange_velocity=1.00*10**-4
+		self.thermal_exchange_velocity=1.00*10**-4
 
 		#Rheology law: what is the temperature dependence of B with T
 		#available: none, paterson and arrhenius
-		obj.rheology_law='Paterson'
-		return obj
+		self.rheology_law='Paterson'
+		return self
 		#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'materials.rho_ice','>',0)
+		md = checkfield(md,'materials.rho_water','>',0)
+		md = checkfield(md,'materials.rho_freshwater','>',0)
+		md = checkfield(md,'materials.mu_water','>',0)
+		md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius'])
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','rho_ice','format','Double')
+		WriteData(fid,'object',self,'fieldname','rho_water','format','Double')
+		WriteData(fid,'object',self,'fieldname','rho_freshwater','format','Double')
+		WriteData(fid,'object',self,'fieldname','mu_water','format','Double')
+		WriteData(fid,'object',self,'fieldname','heatcapacity','format','Double')
+		WriteData(fid,'object',self,'fieldname','latentheat','format','Double')
+		WriteData(fid,'object',self,'fieldname','thermalconductivity','format','Double')
+		WriteData(fid,'object',self,'fieldname','meltingpoint','format','Double')
+		WriteData(fid,'object',self,'fieldname','beta','format','Double')
+		WriteData(fid,'object',self,'fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,'object',self,'fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,'object',self,'fieldname','rheology_B','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','rheology_n','format','DoubleMat','mattype',2)
+		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m	(revision 13101)
@@ -87,4 +87,8 @@
 			md = checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 			md = checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			if (md.mesh.dimension==3),
+				md = checkfield(md,'mesh.z','>=',md.geometry.bed-10^-10,'message','''mesh.z'' lower than bedrock');
+				md = checkfield(md,'mesh.z','<=',md.geometry.surface+10^-10,'message','''mesh.z'' higher than surface elevation');
+			end
 			if (md.mesh.dimension==2),
 				md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
@@ -96,5 +100,5 @@
 			%Solution specific checks
 			switch(solution),
-				case PrognosticSolutionEnum,
+				case PrognosticSolutionEnum(),
 					if md.prognostic.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -102,5 +106,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case BalancethicknessSolutionEnum,
+				case BalancethicknessSolutionEnum(),
 					if md.balancethickness.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -108,5 +112,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case TransientSolutionEnum,
+				case TransientSolutionEnum(),
 					if md.transient.isprognostic & md.prognostic.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -114,5 +118,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case ThermalSolutionEnum,
+				case ThermalSolutionEnum(),
 					md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes');
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/mesh.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/mesh.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/mesh.py	(revision 13101)
@@ -2,9 +2,16 @@
 import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
 from checkfield import *
-from EnumDefinitions import *
 from MatlabFuncs import *
 
-class mesh:
+class mesh(object):
+	"""
+	MESH class definition
+
+	   Usage:
+	      mesh=mesh();
+	"""
+
 	#properties
 	def __init__(self):
@@ -54,58 +61,58 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
-		if obj.dimension==3:
+		if self.dimension==3:
 			string="\n%s"%("      Elements and vertices of the original 2d mesh:")
 			
-			string="%s\n%s"%(string,fielddisplay(obj,"numberofelements2d","number of elements"))
-			string="%s\n%s"%(string,fielddisplay(obj,"numberofvertices2d","number of vertices"))
-			string="%s\n%s"%(string,fielddisplay(obj,"elements2d","index into (x,y,z), coordinates of the vertices"))
-			string="%s\n%s"%(string,fielddisplay(obj,"x2d","vertices x coordinate"))
-			string="%s\n%s"%(string,fielddisplay(obj,"y2d","vertices y coordinate"))
+			string="%s\n%s"%(string,fielddisplay(self,"numberofelements2d","number of elements"))
+			string="%s\n%s"%(string,fielddisplay(self,"numberofvertices2d","number of vertices"))
+			string="%s\n%s"%(string,fielddisplay(self,"elements2d","index into (x,y,z), coordinates of the vertices"))
+			string="%s\n%s"%(string,fielddisplay(self,"x2d","vertices x coordinate"))
+			string="%s\n%s"%(string,fielddisplay(self,"y2d","vertices y coordinate"))
 
 			string="%s\n%s" %(string,"Elements and vertices of the extruded 3d mesh:")
 		else:
 			string="\n%s"%("      Elements and vertices:")
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofelements","number of elements"))
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofvertices","number of vertices"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elements","index into (x,y,z), coordinates of the vertices"))
-		string="%s\n%s"%(string,fielddisplay(obj,"x","vertices x coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"y","vertices y coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"z","vertices z coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofedges","number of edges of the 2d mesh"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","index into (x,y,z), coordinates of the vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"z","vertices z coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
 
 		string="%s%s"%(string,"\n      Properties:")
-		string="%s\n%s"%(string,fielddisplay(obj,"dimension","mesh dimension (2d or 3d)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"numberoflayers","number of extrusion layers"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonbed","lower vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonbed","lower elements flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonsurface","upper vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonsurface","upper elements flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"uppervertex","upper vertex list (NaN for vertex on the upper surface)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"upperelements","upper element list (NaN for element on the upper layer)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowervertex","lower vertex list (NaN for vertex on the lower surface)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowerelements","lower element list (NaN for element on the lower layer"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonboundary","vertices on the boundary of the domain flag list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"segments","edges on domain boundary (vertex1 vertex2 element)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"segmentmarkers","number associated to each segment"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexconnectivity","list of vertices connected to vertex_i"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementconnectivity","list of vertices connected to element_i"))
-		string="%s\n%s"%(string,fielddisplay(obj,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+		string="%s\n%s"%(string,fielddisplay(self,"dimension","mesh dimension (2d or 3d)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberoflayers","number of extrusion layers"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonbed","lower vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonbed","lower elements flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonsurface","upper elements flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (NaN for vertex on the upper surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (NaN for element on the upper layer)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (NaN for vertex on the lower surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (NaN for element on the lower layer"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
+		string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
 
 		string="%s%s"%(string,"\n      Extracted model:")
-		string="%s\n%s"%(string,fielddisplay(obj,"extractedvertices","vertices extracted from the model"))
-		string="%s\n%s"%(string,fielddisplay(obj,"extractedelements","elements extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedvertices","vertices extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedelements","elements extracted from the model"))
 
 		string="%s%s"%(string,"\n      Projection:")
-		string="%s\n%s"%(string,fielddisplay(obj,"lat","vertices latitude"))
-		string="%s\n%s"%(string,fielddisplay(obj,"long","vertices longitude"))
-		string="%s\n%s"%(string,fielddisplay(obj,"hemisphere","Indicate hemisphere ""n"" or ""s"" "))
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude"))
+		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
@@ -115,7 +122,7 @@
 		#give a good memory/time ration. This value can be checked in
 		#trunk/test/Miscellaneous/runme.m
-		obj.average_vertex_connectivity=25
-
-		return obj
+		self.average_vertex_connectivity=25
+
+		return self
 	#}}}
 
@@ -130,6 +137,6 @@
 		else:
 			md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,6])
-		if any(numpy.logical_not(ismember(range(1,md.mesh.numberofvertices+1),md.mesh.elements))):
-			md = checkmessage(md,"orphan nodes have been found. Check the mesh outline")
+		if numpy.any(numpy.logical_not(ismember(range(1,md.mesh.numberofvertices+1),md.mesh.elements))):
+			md.checkmessage("orphan nodes have been found. Check the mesh outline")
 		md = checkfield(md,'mesh.dimension','values',[2,3])
 		md = checkfield(md,'mesh.numberoflayers','>=',0)
@@ -148,20 +155,20 @@
 
 		#Solution specific checks
-		if   solution==PrognosticSolutionEnum:
+		if   solution==PrognosticSolutionEnum():
 			if md.prognostic.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
 				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
 				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
-		elif solution==BalancethicknessSolutionEnum:
+		elif solution==BalancethicknessSolutionEnum():
 			if md.balancethickness.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
 				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
 				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
-		elif solution==TransientSolutionEnum:
+		elif solution==TransientSolutionEnum():
 			if md.transient.isprognostic and md.prognostic.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
 				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
 				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
-		elif solution==ThermalSolutionEnum:
+		elif solution==ThermalSolutionEnum():
 			md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes')
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 13101)
@@ -1,3 +1,3 @@
-%MISCELANEOUS class definition
+%MISCELLANEOUS class definition
 %
 %   Usage:
Index: /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class miscellaneous:
+class miscellaneous(object):
+	"""
+	MISCELLANEOUS class definition
+
+	   Usage:
+	      miscellaneous=miscellaneous();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,17 +24,26 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   miscellaneous parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'notes','notes in a cell of strings'))
-		string="%s\n%s"%(string,fielddisplay(obj,'name','model name'))
-		string="%s\n%s"%(string,fielddisplay(obj,'dummy','empty field to store some data'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'notes','notes in a cell of strings'))
+		string="%s\n%s"%(string,fielddisplay(self,'name','model name'))
+		string="%s\n%s"%(string,fielddisplay(self,'dummy','empty field to store some data'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'miscellaneous.name','empty',1)
+		return md
+	# }}}
+
+	def marshall(self,fid):    #  {{{
+		WriteData(fid,'object',self,'fieldname','name','format','String')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m	(revision 13101)
@@ -91,4 +91,667 @@
 		 end
 		 %}}}
+		 function md = collapse(md)% {{{
+			 %COLLAPSE - collapses a 3d mesh into a 2d mesh
+			 %
+			 %   This routine collapses a 3d model into a 2d model
+			 %   and collapses all the fileds of the 3d model by
+			 %   taking their depth-averaged values
+			 %
+			 %   Usage:
+			 %      md=collapse(md)
+			 %
+			 %   See also: EXTRUDE, MODELEXTRACT
+
+			 %Check that the model is really a 3d model
+			 if ~md.mesh.dimension==3,
+				 error('collapse error message: only 3d mesh can be collapsed')
+			 end
+
+			 %Start with changing alle the fields from the 3d mesh 
+
+			 %drag is limited to nodes that are on the bedrock.
+			 md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+
+			 %p and q (same deal, except for element that are on the bedrock: )
+			 md.friction.p=project2d(md,md.friction.p,1);
+			 md.friction.q=project2d(md,md.friction.q,1);
+
+			 %observations
+			 if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.cost_functions_coefficients), md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers); end;
+			 if numel(md.inversion.min_parameters)>1, md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers); end;
+			 if numel(md.inversion.max_parameters)>1, md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers); end;
+			 if ~isnan(md.surfaceforcings.mass_balance),
+				 md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers); 
+			 end;
+			 if ~isnan(md.balancethickness.thickening_rate), md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers); end;
+
+			 %results
+			 if ~isnan(md.initialization.vx),md.initialization.vx=DepthAverage(md,md.initialization.vx);end;
+			 if ~isnan(md.initialization.vy),md.initialization.vy=DepthAverage(md,md.initialization.vy);end;
+			 if ~isnan(md.initialization.vz),md.initialization.vz=DepthAverage(md,md.initialization.vz);end;
+			 if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
+			 if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
+
+			 %bedinfo and surface info
+			 md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
+			 md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
+			 md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
+			 md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
+
+			 %elementstype
+			 if ~isnan(md.flowequation.element_equation)
+				 md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
+				 md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
+				 md.flowequation.bordermacayeal=project2d(md,md.flowequation.bordermacayeal,1);
+				 md.flowequation.borderpattyn=project2d(md,md.flowequation.borderpattyn,1);
+				 md.flowequation.borderstokes=project2d(md,md.flowequation.borderstokes,1);
+			 end	
+
+			 %boundary conditions
+			 md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
+			 md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
+			 md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
+			 md.diagnostic.referential=project2d(md,md.diagnostic.referential,md.mesh.numberoflayers);
+			 md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
+			 md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+			 %Extrusion of Neumann BC
+			 if ~isnan(md.diagnostic.icefront),
+				 numberofneumann2d=size(md.diagnostic.icefront,1)/(md.mesh.numberoflayers-1);
+				 md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer 
+			 end
+
+			 %materials
+			 md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+			 md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+
+			 %special for thermal modeling:
+			 md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1); 
+			 md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
+
+			 %update of connectivity matrix
+			 md.mesh.average_vertex_connectivity=25;
+
+			 %Collapse the mesh
+			 nodes2d=md.mesh.numberofvertices2d;
+			 elements2d=md.mesh.numberofelements2d;
+
+			 %parameters
+			 md.geometry.surface=project2d(md,md.geometry.surface,1);
+			 md.geometry.thickness=project2d(md,md.geometry.thickness,1);
+			 md.geometry.bed=project2d(md,md.geometry.bed,1);
+			 md.geometry.bathymetry=project2d(md,md.geometry.bathymetry,1);
+			 md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
+			 md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
+			 md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
+			 md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
+			 md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
+			 md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
+			 md.mask.elementonwater=project2d(md,md.mask.elementonwater,1);
+			 md.mask.vertexonwater=project2d(md,md.mask.vertexonwater,1);
+
+			 %lat long
+			 if numel(md.mesh.lat) ==md.mesh.numberofvertices,  md.mesh.lat=project2d(md,md.mesh.lat,1); end
+			 if numel(md.mesh.long)==md.mesh.numberofvertices, md.mesh.long=project2d(md,md.mesh.long,1); end
+
+			 %Initialize with the 2d mesh
+			 md.mesh.x=md.mesh.x2d;
+			 md.mesh.y=md.mesh.y2d;
+			 md.mesh.z=zeros(size(md.mesh.x2d));
+			 md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+			 md.mesh.numberofelements=md.mesh.numberofelements2d;
+			 md.mesh.elements=md.mesh.elements2d;
+
+			 %Keep a trace of lower and upper nodes
+			 md.mesh.lowervertex=NaN;
+			 md.mesh.uppervertex=NaN;
+			 md.mesh.lowerelements=NaN;
+			 md.mesh.upperelements=NaN;
+
+			 %Remove old mesh 
+			 md.mesh.x2d=NaN;
+			 md.mesh.y2d=NaN;
+			 md.mesh.elements2d=NaN;
+			 md.mesh.numberofelements2d=md.mesh.numberofelements;
+			 md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+			 md.mesh.numberoflayers=0;
+
+			 %Update mesh type
+			 md.mesh.dimension=2;
+		 end % }}}
+		 function md2 = extract(md,area) % {{{
+			 %extract - extract a model according to an Argus contour or flag list
+			 %
+			 %   This routine extracts a submodel from a bigger model with respect to a given contour
+			 %   md must be followed by the corresponding exp file or flags list
+			 %   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+			 %   If user wants every element outside the domain to be 
+			 %   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+			 %   an empty string '' will be considered as an empty domain
+			 %   a string 'all' will be considered as the entire domain
+			 %   add an argument 0 if you do not want the elements to be checked (faster)
+			 %
+			 %   Usage:
+			 %      md2=extract(md,area);
+			 %
+			 %   Examples:
+			 %      md2=extract(md,'Domain.exp');
+			 %      md2=extract(md,md.mask.elementonfloatingice);
+			 %
+			 %   See also: EXTRUDE, COLLAPSE
+
+			 %copy model
+			 md1=md;
+
+			 %some checks
+			 if ((nargin~=2) | (nargout~=1)),
+				 help extract
+				 error('extract error message: bad usage');
+			 end
+
+			 %get check option
+			 if (nargin==3 & varargin{1}==0),
+				 checkoutline=0;
+			 else
+				 checkoutline=1;
+			 end
+
+			 %get elements that are inside area
+			 flag_elem=FlagElements(md1,area);
+			 if ~any(flag_elem),
+				 error('extracted model is empty');
+			 end
+
+			 %kick out all elements with 3 dirichlets
+			 spc_elem=find(~flag_elem);
+			 spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
+			 flag=ones(md1.mesh.numberofvertices,1);
+			 flag(spc_node)=0;
+			 pos=find(sum(flag(md1.mesh.elements),2)==0);
+			 flag_elem(pos)=0;
+
+			 %extracted elements and nodes lists
+			 pos_elem=find(flag_elem);
+			 pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
+
+			 %keep track of some fields
+			 numberofvertices1=md1.mesh.numberofvertices;
+			 numberofelements1=md1.mesh.numberofelements;
+			 numberofvertices2=length(pos_node);
+			 numberofelements2=length(pos_elem);
+			 flag_node=zeros(numberofvertices1,1);
+			 flag_node(pos_node)=1;
+
+			 %Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+			 Pelem=zeros(numberofelements1,1);
+			 Pelem(pos_elem)=[1:numberofelements2]';
+			 Pnode=zeros(numberofvertices1,1);
+			 Pnode(pos_node)=[1:numberofvertices2]';
+
+			 %renumber the elements (some node won't exist anymore)
+			 elements_1=md1.mesh.elements;
+			 elements_2=elements_1(pos_elem,:);
+			 elements_2(:,1)=Pnode(elements_2(:,1));
+			 elements_2(:,2)=Pnode(elements_2(:,2));
+			 elements_2(:,3)=Pnode(elements_2(:,3));
+			 if md1.mesh.dimension==3,
+				 elements_2(:,4)=Pnode(elements_2(:,4));
+				 elements_2(:,5)=Pnode(elements_2(:,5));
+				 elements_2(:,6)=Pnode(elements_2(:,6));
+			 end
+
+			 %OK, now create the new model !
+
+			 %take every fields from model
+			 md2=md1;
+
+			 %automatically modify fields
+
+			 %loop over model fields
+			 model_fields=fields(md1);
+			 for i=1:length(model_fields),
+				 %get field
+				 field=md1.(model_fields{i});
+				 fieldsize=size(field);
+				 if isobject(field), %recursive call
+					 object_fields=fields(md1.(model_fields{i}));
+					 for j=1:length(object_fields),
+						 %get field
+						 field=md1.(model_fields{i}).(object_fields{j});
+						 fieldsize=size(field);
+						 %size = number of nodes * n
+						 if fieldsize(1)==numberofvertices1
+							 md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
+						 elseif (fieldsize(1)==numberofvertices1+1)
+							 md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
+							 %size = number of elements * n
+						 elseif fieldsize(1)==numberofelements1
+							 md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
+						 end
+					 end
+				 else
+					 %size = number of nodes * n
+					 if fieldsize(1)==numberofvertices1
+						 md2.(model_fields{i})=field(pos_node,:);
+					 elseif (fieldsize(1)==numberofvertices1+1)
+						 md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
+						 %size = number of elements * n
+					 elseif fieldsize(1)==numberofelements1
+						 md2.(model_fields{i})=field(pos_elem,:);
+					 end
+				 end
+			 end
+
+			 %modify some specific fields
+
+			 %Mesh
+			 md2.mesh.numberofelements=numberofelements2;
+			 md2.mesh.numberofvertices=numberofvertices2;
+			 md2.mesh.elements=elements_2;
+
+			 %mesh.uppervertex mesh.lowervertex
+			 if md1.mesh.dimension==3
+				 md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
+				 pos=find(~isnan(md2.mesh.uppervertex));
+				 md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
+
+				 md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
+				 pos=find(~isnan(md2.mesh.lowervertex));
+				 md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
+
+				 md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
+				 pos=find(~isnan(md2.mesh.upperelements));
+				 md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
+
+				 md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
+				 pos=find(~isnan(md2.mesh.lowerelements));
+				 md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
+			 end
+
+			 %Initial 2d mesh 
+			 if md1.mesh.dimension==3
+				 flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
+				 pos_elem_2d=find(flag_elem_2d);
+				 flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
+				 pos_node_2d=find(flag_node_2d);
+
+				 md2.mesh.numberofelements2d=length(pos_elem_2d);
+				 md2.mesh.numberofvertices2d=length(pos_node_2d);
+				 md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
+				 md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
+				 md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
+				 md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
+
+				 md2.mesh.x2d=md1.mesh.x(pos_node_2d);
+				 md2.mesh.y2d=md1.mesh.y(pos_node_2d);
+			 end
+
+			 %Edges
+			 if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
+				 %renumber first two columns
+				 pos=find(md2.mesh.edges(:,4)~=-1);
+				 md2.mesh.edges(:  ,1)=Pnode(md2.mesh.edges(:,1)); 
+				 md2.mesh.edges(:  ,2)=Pnode(md2.mesh.edges(:,2)); 
+				 md2.mesh.edges(:  ,3)=Pelem(md2.mesh.edges(:,3));
+				 md2.mesh.edges(pos,4)=Pelem(md2.mesh.edges(pos,4));
+				 %remove edges when the 2 vertices are not in the domain.
+				 md2.mesh.edges=md2.mesh.edges(find(md2.mesh.edges(:,1) & md2.mesh.edges(:,2)),:);
+				 %Replace all zeros by -1 in the last two columns;
+				 pos=find(md2.mesh.edges(:,3)==0);
+				 md2.mesh.edges(pos,3)=-1;
+				 pos=find(md2.mesh.edges(:,4)==0);
+				 md2.mesh.edges(pos,4)=-1;
+				 %Invert -1 on the third column with last column (Also invert first two columns!!)
+				 pos=find(md2.mesh.edges(:,3)==-1);
+				 md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
+				 md2.mesh.edges(pos,4)=-1;
+				 values=md2.mesh.edges(pos,2);
+				 md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
+				 md2.mesh.edges(pos,1)=values;
+				 %Finally remove edges that do not belong to any element
+				 pos=find(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
+				 md2.mesh.edges(pos,:)=[];
+			 end
+
+			 %Penalties
+			 if ~isnan(md2.diagnostic.vertex_pairing),
+				 for i=1:size(md1.diagnostic.vertex_pairing,1);
+					 md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
+				 end
+				 md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
+			 end
+			 if ~isnan(md2.prognostic.vertex_pairing),
+				 for i=1:size(md1.prognostic.vertex_pairing,1);
+					 md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
+				 end
+				 md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
+			 end
+
+			 %recreate segments
+			 if md1.mesh.dimension==2
+				 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+				 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+				 md2.mesh.segments=contourenvelope(md2);
+				 md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+			 else
+				 %First do the connectivity for the contourenvelope in 2d
+				 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d);
+				 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity);
+				 md2.mesh.segments=contourenvelope(md2);
+				 md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+				 md2.mesh.vertexonboundary=repmat(md2.mesh.vertexonboundary,md2.mesh.numberoflayers,1);
+				 %Then do it for 3d as usual
+				 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+				 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+			 end
+
+			 %Boundary conditions: Dirichlets on new boundary
+			 %Catch the elements that have not been extracted
+			 orphans_elem=find(~flag_elem);
+			 orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
+			 %Figure out which node are on the boundary between md2 and md1
+			 nodestoflag1=intersect(orphans_node,pos_node);
+			 nodestoflag2=Pnode(nodestoflag1);
+			 if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
+				 if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
+					 md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+					 md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+				 else
+					 md2.diagnostic.spcvx(nodestoflag2)=NaN;
+					 md2.diagnostic.spcvy(nodestoflag2)=NaN;
+					 disp(' ')
+					 disp('!! extract warning: spc values should be checked !!')
+					 disp(' ')
+				 end
+				 %put 0 for vz
+				 md2.diagnostic.spcvz(nodestoflag2)=0;
+			 end
+			 if ~isnan(md1.thermal.spctemperature),
+				 md2.thermal.spctemperature(nodestoflag2,1)=1;
+			 end
+
+			 %Diagnostic
+			 if ~isnan(md2.diagnostic.icefront)
+				 md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1)); 
+				 md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2)); 
+				 md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
+				 if md1.mesh.dimension==3
+					 md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3)); 
+					 md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4)); 
+				 end
+				 md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
+			 end
+
+			 %Results fields
+			 if isstruct(md1.results),
+				 md2.results=struct();
+				 solutionfields=fields(md1.results);
+				 for i=1:length(solutionfields),
+					 %get subfields
+					 solutionsubfields=fields(md1.results.(solutionfields{i}));
+					 for j=1:length(solutionsubfields),
+						 field=md1.results.(solutionfields{i}).(solutionsubfields{j});
+						 if length(field)==numberofvertices1,
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
+						 elseif length(field)==numberofelements1,
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
+						 else
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
+						 end
+					 end
+				 end
+			 end
+
+			 %Keep track of pos_node and pos_elem
+			 md2.mesh.extractedvertices=pos_node;
+			 md2.mesh.extractedelements=pos_elem;
+		 end % }}}
+		 function md = extrude(md,varargin) % {{{
+			 %EXTRUDE - vertically extrude a 2d mesh
+			 %
+			 %   vertically extrude a 2d mesh and create corresponding 3d mesh.
+			 %   The vertical distribution can:
+			 %    - follow a polynomial law
+			 %    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+			 %    - be discribed by a list of coefficients (between 0 and 1)
+			 %   
+			 %
+			 %   Usage:
+			 %      md=extrude(md,numlayers,extrusionexponent);
+			 %      md=extrude(md,numlayers,lowerexponent,upperexponent);
+			 %      md=extrude(md,listofcoefficients);
+			 %
+			 %   Example:
+			 %      md=extrude(md,8,3);
+			 %      md=extrude(md,8,3,2);
+			 %      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
+			 %
+			 %   See also: MODELEXTRACT, COLLAPSE
+
+			 %some checks on list of arguments
+			 if ((nargin>4) | (nargin<2) | (nargout~=1)),
+				 help extrude;
+				 error('extrude error message');
+			 end
+
+			 %Extrude the mesh
+			 if nargin==2, %list of coefficients
+				 list=varargin{1};
+				 if any(list<0) | any(list>1),
+					 error('extrusioncoefficients must be between 0 and 1');
+				 end
+				 extrusionlist=sort(unique([list(:);0;1]));
+				 numlayers=length(extrusionlist);
+			 elseif nargin==3, %one polynomial law
+				 if varargin{2}<=0,
+					 help extrude;
+					 error('extrusionexponent must be >=0');
+				 end
+				 numlayers=varargin{1};
+				 extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
+			 elseif nargin==4, %two polynomial laws
+				 numlayers=varargin{1};
+				 lowerexp=varargin{2};
+				 upperexp=varargin{3};
+
+				 if varargin{2}<=0 | varargin{3}<=0,
+					 help extrude;
+					 error('lower and upper extrusionexponents must be >=0');
+				 end
+
+				 lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
+				 upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
+				 extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
+
+			 end
+
+			 if numlayers<2,
+				 error('number of layers should be at least 2');
+			 end
+			 if md.mesh.dimension==3,
+				 error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+			 end
+
+			 %Initialize with the 2d mesh
+			 x3d=[]; 
+			 y3d=[];
+			 z3d=[];  %the lower node is on the bed
+			 thickness3d=md.geometry.thickness; %thickness and bed for these nodes
+			 bed3d=md.geometry.bed;
+
+			 %Create the new layers
+			 for i=1:numlayers,
+				 x3d=[x3d; md.mesh.x]; 
+				 y3d=[y3d; md.mesh.y];
+				 %nodes are distributed between bed and surface accordingly to the given exponent
+				 z3d=[z3d; bed3d+thickness3d*extrusionlist(i)]; 
+			 end
+			 number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			 %Extrude elements 
+			 elements3d=[];
+			 for i=1:numlayers-1,
+				 elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
+			 end
+			 number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			 %Keep a trace of lower and upper nodes
+			 mesh.lowervertex=NaN*ones(number_nodes3d,1);
+			 mesh.uppervertex=NaN*ones(number_nodes3d,1);
+			 mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
+			 mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
+			 md.mesh.lowervertex=mesh.lowervertex;
+			 md.mesh.uppervertex=mesh.uppervertex;
+
+			 %same for lower and upper elements
+			 mesh.lowerelements=NaN*ones(number_el3d,1);
+			 mesh.upperelements=NaN*ones(number_el3d,1);
+			 mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
+			 mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
+			 md.mesh.lowerelements=mesh.lowerelements;
+			 md.mesh.upperelements=mesh.upperelements;
+
+			 %Save old mesh 
+			 md.mesh.x2d=md.mesh.x;
+			 md.mesh.y2d=md.mesh.y;
+			 md.mesh.elements2d=md.mesh.elements;
+			 md.mesh.numberofelements2d=md.mesh.numberofelements;
+			 md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+
+			 %Update mesh type
+			 md.mesh.dimension=3;
+
+			 %Build global 3d mesh 
+			 md.mesh.elements=elements3d;
+			 md.mesh.x=x3d;
+			 md.mesh.y=y3d;
+			 md.mesh.z=z3d;
+			 md.mesh.numberofelements=number_el3d;
+			 md.mesh.numberofvertices=number_nodes3d;
+			 md.mesh.numberoflayers=numlayers;
+
+			 %Ok, now deal with the other fields from the 2d mesh:
+
+			 %lat long
+			 md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
+			 md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
+
+			 %drag coefficient is limited to nodes that are on the bedrock.
+			 md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
+
+			 %p and q (same deal, except for element that are on the bedrock: )
+			 md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
+			 md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
+
+			 %observations
+			 md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
+			 md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
+			 md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
+			 md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
+			 md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node');
+			 md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
+			 md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node');
+
+			 %results
+			 if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
+			 if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
+			 if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
+			 if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
+			 if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
+			 if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
+
+			 %bedinfo and surface info
+			 md.mesh.elementonbed=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
+			 md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
+			 md.mesh.vertexonbed=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
+			 md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
+
+			 %elementstype
+			 if ~isnan(md.flowequation.element_equation)
+				 oldelements_type=md.flowequation.element_equation;
+				 md.flowequation.element_equation=zeros(number_el3d,1);
+				 md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
+			 end
+
+			 %verticestype
+			 if ~isnan(md.flowequation.vertex_equation)
+				 oldvertices_type=md.flowequation.vertex_equation;
+				 md.flowequation.vertex_equation=zeros(number_nodes3d,1);
+				 md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
+			 end
+			 md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
+			 md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
+			 md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node');
+
+			 %boundary conditions
+			 md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
+			 md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
+			 md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
+			 md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+			 md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
+			 md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
+			 md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
+
+			 %in 3d, pressureload: [node1 node2 node3 node4 element]
+			 pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer 
+			 pressureload=[];
+			 for i=1:numlayers-1,
+				 pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
+			 end
+			 md.diagnostic.icefront=pressureload;
+
+			 %connectivity
+			 md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
+			 md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
+			 for i=2:numlayers-1,
+				 md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
+					 =md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
+			 end
+			 md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+			 %materials
+			 md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
+			 md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
+
+			 %parameters
+			 md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
+			 md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+			 md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
+			 md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
+			 md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
+			 md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+			 md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
+			 md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
+			 md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
+			 md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
+			 md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
+			 md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
+			 if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+			 if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
+			 if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
+			 if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
+			 if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node');end
+			 if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node');end
+			 if(md.surfaceforcings.isdelta18o),md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node');end
+
+			 %Put lithostatic pressure if there is an existing pressure
+			 if ~isnan(md.initialization.pressure),
+				 md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
+			 end
+
+			 %special for thermal modeling:
+			 md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1); 
+			 if ~isnan(md.basalforcings.geothermalflux)
+				 md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
+			 end
+
+			 %increase connectivity if less than 25:
+			 if md.mesh.average_vertex_connectivity<=25,
+				 md.mesh.average_vertex_connectivity=100;
+			 end
+			end % }}}
 		 function md = structtomodel(md,structmd) % {{{
 
@@ -385,8 +1048,8 @@
 			 md.settings         = settings();
 			 md.solver           = solver();
-			 if ismumps,
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum,mumpsoptions);
+			 if ismumps(),
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
 			 else
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum,iluasmoptions);
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
 			 end
 			 md.cluster          = generic();
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py	(revision 13101)
@@ -33,4 +33,7 @@
 from private import private
 from EnumDefinitions import *
+from ismumps import *
+from mumpsoptions import *
+from iluasmoptions import *
 #}}}
 
@@ -56,9 +59,8 @@
 		self.settings         = settings()
 		self.solver           = solver()
-#		need EnumToString for these to work
-#		if ismumps:
-#			md.solver.addoptions(DiagnosticVertAnalysisEnum(),mumpsoptions)
-#		else:
-#			md.solver.addoptions(DiagnosticVertAnalysisEnum(),iluasmoptions)
+		if ismumps():
+			self.solver.addoptions(DiagnosticVertAnalysisEnum(),mumpsoptions())
+		else:
+			self.solver.addoptions(DiagnosticVertAnalysisEnum(),iluasmoptions())
 		self.cluster          = generic()
 
@@ -116,5 +118,5 @@
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results'"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 13101)
@@ -6,43 +6,59 @@
 classdef planet < model
     properties (SetAccess=public) %Planet fields
-		 % {{{
-		 %Planet specific fields
-		 r=NaN;
-		 theta=NaN;
-		 phi=NaN;
+	 end
+	 methods
+		 function md = planet(varargin) % {{{
+
+			 switch nargin
+				 case 0
+					 md=setdefaultparameters(md);
+				 otherwise
+					 error('planet constructor error message: 0 of 1 argument only in input.');
+				 end
+		 end
+		 %}}}
+		 function md = setdefaultparameters(md) % {{{
+
+			 %initialize subclasses
+			 md.mesh             = planetmesh();
+			 md.mask             = mask();
+			 md.constants        = constants();
+			 md.geometry         = geometry();
+			 md.initialization   = initialization();
+			 md.surfaceforcings  = surfaceforcings();
+			 md.basalforcings    = basalforcings();
+			 md.friction         = friction();
+			 md.rifts            = rifts();
+			 md.timestepping     = timestepping();
+			 md.groundingline    = groundingline();
+			 md.materials        = materials();
+			 md.flowequation     = flowequation();
+			 md.debug            = debug();
+			 md.verbose          = verbose('solution',true,'qmu',true,'control',true);
+			 md.settings         = settings();
+			 md.solver           = solver();
+			 if ismumps(),
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
+			 else
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
+			 end
+			 md.cluster          = generic();
+			 md.balancethickness = balancethickness();
+			 md.diagnostic       = diagnostic();
+			 md.hydrology        = hydrology();
+			 md.prognostic       = prognostic();
+			 md.thermal          = thermal();
+			 md.steadystate      = steadystate();
+			 md.transient        = transient();
+			 md.autodiff         = autodiff();
+			 md.flaim            = flaim();
+			 md.inversion        = inversion();
+			 md.qmu              = qmu();
+			 md.radaroverlay     = radaroverlay();
+			 md.results          = struct();
+			 md.miscellaneous    = miscellaneous();
+			 md.private          = private();
+		 end
 		 %}}}
 	 end
-	 methods
-		function md=planetmesh(md,varargin) % {{{
-		%PLANETMESH: build 2d shell mesh
-		%
-		% Usage: md=planetmesh(md,'method','mixed','radius',6378000,'angleresol',1);
-		%        md=planetmesh(md,'method','tria','shape','iso','radius',6378000,'refinement',5);
-		%
-
-		%recover options
-		options=pairoptions(varargin{:});
-
-		method=getfieldvalue(options,'method','mixed');
-		
-		if strcmpi(method,'mixed'),
-			%recover radius and angleresol: 
-			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
-			angleresol=getfieldvalue(options,'angleresol',10); %10 degree resolution
-			
-			%call mixed mesh 
-			md=planetmixedmesh(md,radius,angleresol);
-		else
-			%recover radius, shape and level of refinmenet
-			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
-			refinement=getfieldvalue(options,'refinement',5); %refine 5 times
-			shape=getfieldvalue(options,'shape','ico'); 
-			
-			%call triangular mesh
-			md=planettrimesh(md,shape,radius,refinement);
-		end
-
-		end
-		% }}}
-	 end
  end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/modellist.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/modellist.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/modellist.m	(revision 13101)
@@ -10,4 +10,116 @@
 	end
 	methods
+		function md_list=modelsextract(md,flags,minel,varargin) % {{{
+			%modelsextract - extract several self contained models according to a list of element flags.
+			%
+			%   The difference between this routine and the modelextract.m routine (without an 's') is that 
+			%   as many models are extracted as there are closed contours defined in area. 
+			%   This routine is needed for example when doing data assimilation of ice shelves in Antarctica. 
+			%   Many independent ice shelves are present, and we don't want data assimilation on one ice shelf 
+			%   to be hindered by another totally independent ice shelf.
+			%
+			%   Usage:
+			%      md_list=modelsextract(md,elementfalgs,minel);
+			%
+			%   Examples:
+			%      md_list=modelsextract(md,md.mask.elementonfloatingice,1000);
+			%
+			%   See also: EXTRUDE, COLLAPSE, MODELEXTRACT
+
+			disp('selecting pools of elements');
+			%go through flags and build as many independent element flags as there are groups of connected 1s
+			%in flags.
+
+			%2D or 3D?
+			if md.mesh.dimension==3,
+				numberofelements=md.mesh.numberofelements2d; %this will be forgotten when we get out.
+				flags=project2d(md,flags,1);
+			else
+				numberofelements=md.mesh.numberofelements;
+			end
+
+			%recover extra arguments: 
+			distance=0;
+			if nargin==4,
+				distance=varargin{1};
+			end
+
+			flag_list=cell(0,1);
+
+			for i=1:size(flags,1),
+
+				if (flags(i)),
+
+					%ok, we are sure element i is part of a new pool.
+					pool=zeros(numberofelements,1);
+					pool=PropagateFlagsFromConnectivity(md.mesh.elementconnectivity,pool,i,flags);
+					flag_list{end+1,1}=pool;
+
+					%speed up rest of computation by taking pool out of flags: 
+					pos=find(pool);flags(pos)=0;
+
+				end
+			end
+
+			%go through flag_list and discard any pool of less than minel elements: 
+			ex_pos=[];
+			for i=1:length(flag_list),
+				if length(find(flag_list{i}))<minel,
+					ex_pos=[ex_pos; i];
+				end
+			end
+			flag_list(ex_pos)=[];
+
+			%now, if distance was specified, expand the flag_list by distance km: 
+			if distance,
+				for i=1:length(flag_list),
+					flag_list{i}=PropagateFlagsUntilDistance(md,flag_list{i},distance);
+				end
+			end
+
+			%now, go use the pools of flags to extract models: 
+			disp(['extracting ' num2str(size(flag_list,1)) ' models']);
+			models=cell(0,1);
+
+			for i=1:size(flag_list,1),
+				disp(['   ' num2str(i) '/' num2str(size(flag_list,1))]);
+				if md.mesh.dimension==3,
+					flags2d=flag_list{i};
+					realflags=project3d(md,flags2d,'element');
+				else
+					realflags=flag_list{i};
+				end
+				models{end+1,1}=modelextract(md,realflags);
+			end
+
+			%return model list
+			md_list=modellist(models);
+
+		end %end of this function }}}
+		function md_list=modelsextractfromdomains(md,directory) % {{{
+			%modelsextractfromdomains- extract several self contained models according to a list of domains
+			%
+			%   Usage:
+			%      md_list=modelsextractfromdomains(md,'Basins/');
+			%
+			%   Examples:
+			%      md_list=modelsextract(md,'Basins/');
+			%
+			%   See also: MODELSEXTRACTS, MODELEXTRACT
+
+			%go into directory and get list of files.
+			cd(directory);
+			basins=listfiles;
+			cd ..
+
+			models=cell(0,1);
+			for i=1:length(basins),
+				models{end+1,1}=modelextract(md,[directory '/' basins{i}]);
+			end
+
+			%return model list: 
+			md_list=modellist(models);
+
+		end % }}}
 		function obj = modellist(varargin) % {{{
 
@@ -180,2 +292,96 @@
 	end
 end
+
+function BuildMultipleQueueingScript(cluster,name,executionpath,codepath)% {{{
+%BUILDMULTIPLEQUEUEINGSCRIPT - 
+%
+%   Usage:
+%      BuildMultipleQueueingScript(executionpath,codepath)
+
+disp('building queueing script');
+
+%First try and figure out if there is a special script for this particular cluster
+function_name=['BuildMultipleQueueingScript' cluster];
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='BuildMultipleQueueingScriptgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(name,executionpath,codepath);']);
+else
+	%Call the generic BuildQueueingScript:
+	BuildMultipleQueueingScriptGeneric(name,executionpath,codepath);
+end
+end % }}}
+function BuildQueueingScriptgemini(name,executionpath,codepath)% {{{
+%BUILDQUEUEINGSCRIPTGEMINI - ...
+%
+%   Usage:
+%      BuildQueueingScriptgemini(md,executionpath,codepath)
+
+scriptname=[name '.queue'];
+
+fid=fopen(scriptname,'w');
+if fid==-1,
+	error(['BuildQueueingScriptgeminierror message: could not open ' scriptname ' file for ascii writing']);
+end
+
+fprintf(fid,'#!/bin/sh\n');
+fprintf(fid,'cd %s\n',executionpath);
+fprintf(fid,'mkdir %s\n',name);
+fprintf(fid,'cd %s\n',name);
+fprintf(fid,'mv ../ModelList.tar.gz ./\n');
+fprintf(fid,'tar -zxvf ModelList.tar.gz\n');
+fprintf(fid,'foreach i (%s-*vs*.queue)\n',name);
+fprintf(fid,'qsub $i\n');
+fprintf(fid,'end\n');
+fclose(fid);
+end% }}}
+function LaunchMultipleQueueJob(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOB - ...
+%
+%   Usage:
+%      LaunchMultipleQueueJob(executionpath)
+
+%First try and figure out if there is a special script for thie particular cluster
+function_name=['LaunchMultipleQueueJob' cluster];
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='LaunchMultipleQueueJobgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(cluster,name,executionpath);']);
+else
+	%Call the generic LaunchMultipleQueueJob:
+	LaunchMultipleQueueJobGeneric(cluster,name,executionpath);
+end
+end% }}}
+function md=LaunchMultipleQueueJobgemini(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOBGEMINI - Launch multiple queueing script on Gemini cluster
+%
+%   Usage:
+%      LaunchMultipleQueueJobgemini(cluster,name,executionpath)
+
+
+%first, check we have the binary file and the queueing script
+if ~exist([ name '.queue'],'file'),
+	error('LaunchMultipleQueueJobgemini error message: queueing script issing, cannot go forward');
+end
+
+if ~exist('ModelList.tar.gz','file'),
+	error('LaunchMultipleQueueJobgemini error message: inputs models file missing, cannot go forward');
+end
+
+%upload both files to cluster
+disp('uploading input file,  queueing script and variables script');
+eval(['!scp ModelList.tar.gz ' name '.queue '  cluster ':' executionpath]);
+
+disp('launching solution sequence on remote cluster');
+issmssh(cluster,login,['"cd ' executionpath ' && source ' name '.queue "']);
+end% }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py	(revision 13101)
@@ -36,5 +36,5 @@
 		#go through arg and build list of objects
 		for i in xrange(numoptions):
-			if isinstance(arg[2*i],str):
+			if isinstance(arg[2*i],(str,unicode)):
 				self.list[arg[2*i]] = arg[2*i+1];
 			else:
@@ -45,5 +45,5 @@
 	def addfield(self,field,value):    # {{{
 		"""ADDFIELD - add a field to an options list"""
-		if isinstance(field,str):
+		if isinstance(field,(str,unicode)):
 			if field in self.list:
 				print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
@@ -53,6 +53,6 @@
 	def addfielddefault(self,field,value):    # {{{
 		"""ADDFIELDDEFAULT - add a field to an options list if it does not exist"""
-		if isinstance(field,str):
-			if not field in self.list:
+		if isinstance(field,(str,unicode)):
+			if field not in self.list:
 				self.list[field] = value
 	# }}}
@@ -100,5 +100,5 @@
 			s+="   list: (%ix%i)\n\n" % (len(self.list),2)
 			for item in self.list.iteritems():
-				if   isinstance(item[1],str):
+				if   isinstance(item[1],(str,unicode)):
 					s+="     field: %-10s value: '%s'\n" % (item[0],item[1])
 				elif isinstance(item[1],(bool,int,long,float)):
@@ -117,5 +117,5 @@
 		if field == None or field == '':
 			raise ValueError('exist error message: bad usage');
-		if not isinstance(field,str):
+		if not isinstance(field,(str,unicode)):
 			raise TypeError("exist error message: field '%s' should be a string." % str(field));
 
@@ -157,5 +157,5 @@
 		if field == None or field == '':
 			raise ValueError('getfieldvalue error message: bad usage');
-		if not isinstance(field,str):
+		if not isinstance(field,(str,unicode)):
 			raise TypeError("getfieldvalue error message: field '%s' should be a string." % str(field));
 
@@ -204,5 +204,5 @@
 
 			#Write option value
-			if   isinstance(value,str):
+			if   isinstance(value,(str,unicode)):
 				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
 			elif isinstance(value,(bool,int,long,float)):
Index: /issm/branches/trunk-jpl-damage/src/m/classes/planetmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/planetmesh.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/planetmesh.m	(revision 13101)
@@ -6,4 +6,7 @@
 classdef planetmesh
 	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN;
 		r                           = NaN;
 		theta                       = NaN;
@@ -42,4 +45,7 @@
 		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]);
@@ -68,13 +74,13 @@
 			%Solution specific checks
 			switch(solution),
-				case PrognosticSolutionEnum,
+				case PrognosticSolutionEnum(),
 					if md.prognostic.stabilization==3,
 						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
 					end
-				case TransientSolutionEnum,
+				case TransientSolutionEnum(),
 					if md.transient.isprognostic & md.prognostic.stabilization==3,
 						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
 					end
-				case ThermalSolutionEnum,
+				case ThermalSolutionEnum(),
 					md = checkfield(md,'planetmesh.dimension','values',3,'message','thermal solution only supported on 3d planetmeshes');
 			end
@@ -87,4 +93,7 @@
 			fielddisplay(obj,'numberofvertices','number of vertices');
 			fielddisplay(obj,'elements','index into (x,y,z), coordinates of the vertices');
+			fielddisplay(obj,'x','vertices x coordinate');
+			fielddisplay(obj,'y','vertices y coordinate');
+			fielddisplay(obj,'z','vertices z coordinate');
 			fielddisplay(obj,'r','vertices r coordinate');
 			fielddisplay(obj,'theta','vertices theta coordinate');
@@ -101,4 +110,7 @@
 		end % }}}
 		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/private.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/private.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/private.py	(revision 13101)
@@ -1,13 +1,22 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
 
-class private:
+class private(object):
+	"""
+	PRIVATE class definition
+
+	   Usage:
+	      private=private();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.isconsistent = True;
+		self.isconsistent = True
 		self.runtimename  = ''
 		self.bamg         = {}
-		self.solution     = '';
+		self.solution     = ''
 
 		#set defaults
@@ -15,18 +24,22 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   private parameters: do not change'
 
-		string="%s\n%s"%(string,fielddisplay(obj,'isconsistent','is model self consistent'))
-		string="%s\n%s"%(string,fielddisplay(obj,'runtimename','name of the run launched'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain'))
-		string="%s\n%s"%(string,fielddisplay(obj,'solution','type of solution launched'))
+		string="%s\n%s"%(string,fielddisplay(self,'isconsistent','is model self consistent'))
+		string="%s\n%s"%(string,fielddisplay(self,'runtimename','name of the run launched'))
+		string="%s\n%s"%(string,fielddisplay(self,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain'))
+		string="%s\n%s"%(string,fielddisplay(self,'solution','type of solution launched'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 13101)
@@ -38,6 +38,6 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			%Early return,
-			if ~ismember(PrognosticAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isprognostic==0), return; end
+			%Early return
+			if ~ismember(PrognosticAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isprognostic==0), return; end
 
 			md = checkfield(md,'prognostic.spcthickness','forcing',1);
@@ -62,5 +62,5 @@
 			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
-			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum);
+			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum());
 			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
Index: /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.py	(revision 13101)
@@ -1,6 +1,17 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
 
-class prognostic:
+class prognostic(object):
+	"""
+	PROGNOSTIC class definition
+
+	   Usage:
+	      prognostic=prognostic();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,31 +28,54 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   Prognostic solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'min_thickness','minimum ice thickness allowed'))
-		string="%s\n%s"%(string,fielddisplay(obj,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum ice thickness allowed'))
+		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
-		obj.stabilization=1
+		self.stabilization=1
 
 		#Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#Minimum ice thickness that can be used
-		obj.min_thickness=1
+		self.min_thickness=1
 
 		#Hydrostatic adjustment
-		obj.hydrostatic_adjustment='Absolute'
+		self.hydrostatic_adjustment='Absolute'
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (PrognosticAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isprognostic):
+			return md
+
+		md = checkfield(md,'prognostic.spcthickness','forcing',1)
+		md = checkfield(md,'prognostic.hydrostatic_adjustment','values',['Absolute','Incremental'])
+		md = checkfield(md,'prognostic.stabilization','values',[0,1,2,3])
+		md = checkfield(md,'prognostic.min_thickness','>',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
+		WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum())
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m	(revision 13101)
@@ -47,18 +47,6 @@
 					md = checkmessage(md,['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
 				end
-				if find(md.qmu.partition)>=md.mesh.numberofvertices,
-					md = checkmessage(md,['user supplied partition should be indexed from 0 (c-convention)']);
-				end
 				if min(md.qmu.partition)~=0,
 					md = checkmessage(md,['partition vector not indexed from 0 on']);
-				end
-				if max(md.qmu.partition)>=md.mesh.numberofvertices,
-					md = checkmessage(md,['partition vector cannot have maximum index larger than number of nodes']);
-				end
-				if ~isempty(find(md.qmu.partition<0)),
-					md = checkmessage(md,['partition vector cannot have values less than 0']);
-				end
-				if ~isempty(find(md.qmu.partition>=md.qmu.numberofpartitions)),
-					md = checkmessage(md,['partition vector cannot have values more than md.qmu.numberofpartitions-1']);
 				end
 				if max(md.qmu.partition)>=md.qmu.numberofpartitions,
@@ -140,6 +128,6 @@
 				end
 			end
-			fielddisplay(obj,'partition','user provided mesh partitionition, defaults to metis if not specified') 
-			fielddisplay(obj,'numberofpartitions','number of partitions for semi-descrete qmu') 
+			fielddisplay(obj,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+			fielddisplay(obj,'numberofpartitions','number of partitions for semi-discrete qmu') 
 			fielddisplay(obj,'variabledescriptors','');
 			fielddisplay(obj,'responsedescriptors','');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/qmu.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/qmu.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/qmu.py	(revision 13101)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+from MatlabFuncs import *
 
-class qmu:
+class qmu(object):
+	"""
+	QMU class definition
+
+	   Usage:
+	      qmu=qmu();
+	"""
+
 	#properties
 	def __init__(self):
@@ -27,13 +39,116 @@
 
 		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		string="   qmu parameters: not implemented yet!"
-		return string
-		#}}}
-		
-	def setdefaultparameters(obj):
+
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not md.qmu.isdakota:
+			return
+
+		if not md.qmu.params.evaluation_concurrency==1:
+			md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
+		if md.qmu.partition:
+			if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices:
+				md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1")
+			if not min(md.qmu.partition)==0:
+				md.checkmessage("partition vector not indexed from 0 on")
+			if max(md.qmu.partition)>=md.qmu.numberofpartitions:
+				md.checkmessage("for qmu analysis, partitioning vector cannot go over npart, number of partition areas")
+
+		if not strcmpi(md.cluster.name,'none'):
+			if not md.settings.waitonlock:
+				md.checkmessage("waitonlock should be activated when running qmu in parallel mode!")
+
+		return md
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ='   qmu parameters:\n'
+
+		s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
+		for i,variable in enumerate(self.variables):
+			s+="         variables%s:  (arrays of each variable class)\n" % \
+				string_dim(self.variables,i)
+			fnames=vars(variable)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="'            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
+
+		for i,response in enumerate(self.responses):
+			s+="         responses%s:  (arrays of each response class)\n" % \
+				string_dim(self.responses,i)
+			fnames=vars(response)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
+
+		s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 
+
+		for i,method in enumerate(self.method):
+			if isinstance(method,'dakota_method'):
+				s+="            method%s :    '%s'\n" % \
+					(string_dim(method,i),method.method)
+
+		for i,param in enumerate(self.params):
+			s+="         params%s:  (array of method-independent parameters)\n" % \
+				string_dim(self.params,i)
+			fnames=vars(param)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s: %s\n" % \
+					(maxlen+1,fname,any2str(getattr(param,fname)))
+
+		for i,result in enumerate(self.results):
+			s+="         results%s:  (information from dakota files)\n" % \
+				string_dim(self.results,i)
+			fnames=vars(result)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
+
+		s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+		s+="%s\n" % fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
+		s+="%s\n" % fielddisplay(self,'variabledescriptors','')
+		s+="%s\n" % fielddisplay(self,'responsedescriptors','')
+		s+="%s\n" % fielddisplay(self,'method','array of dakota_method class')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_segments','')
+		s+="%s\n" % fielddisplay(self,'adjacency','')
+		s+="%s\n" % fielddisplay(self,'vertex_weight','weight applied to each mesh vertex')
+
+		return s
+	# }}}
+		
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
+		if not self.isdakota:
+			return
+		WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','numberofpartitions','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofresponses','format','Integer')
+		WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray')
+		WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray')
+		WriteData(fid,'object',self,'fieldname','mass_flux_segments','format','MatArray')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/radaroverlay.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/radaroverlay.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/radaroverlay.py	(revision 13101)
@@ -2,5 +2,12 @@
 from fielddisplay import fielddisplay
 
-class radaroverlay:
+class radaroverlay(object):
+	"""
+	RADAROVERLAY class definition
+
+	   Usage:
+	      radaroverlay=radaroverlay();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +21,16 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   radaroverlay parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'pwr','radar power image (matrix)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'x','corresponding x coordinates'))
-		string="%s\n%s"%(string,fielddisplay(obj,'y','corresponding y coordinates'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'pwr','radar power image (matrix)'))
+		string="%s\n%s"%(string,fielddisplay(self,'x','corresponding x coordinates'))
+		string="%s\n%s"%(string,fielddisplay(self,'y','corresponding y coordinates'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m	(revision 13101)
@@ -79,6 +79,6 @@
 			end
 
-			WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum,'format','Integer');
-			WriteData(fid,'data',data,'enum',RiftsRiftstructEnum,'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer');
+			WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3);
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/rifts.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/rifts.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/rifts.py	(revision 13101)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+from isnans import *
 
-class rifts:
+class rifts(object):
+	"""
+	RIFTS class definition
+
+	   Usage:
+	      rifts=rifts();
+	"""
+
 	#properties
 	def __init__(self):
@@ -13,16 +25,67 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   rifts parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'riftproperties',''))
+		string="%s\n\n%s"%(string,fielddisplay(self,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)'))
+		string="%s\n%s"%(string,fielddisplay(self,'riftproperties',''))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		if numrifts:
+			if not md.mesh.dimension==2:
+				md.checkmessage("models with rifts are only supported in 2d for now!")
+			if not isinstance(self.riftstruct,list):
+				md.checkmessage("rifts.riftstruct should be a structure!")
+			if numpy.any(md.mesh.segmentmarkers>=2):
+				#We have segments with rift markers, but no rift structure!
+				md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
+			md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
+		else:
+			if numpy.any(numpy.logical_not(isnans(self.riftstruct))):
+				md.checkmessage("riftstruct shoud be NaN since numrifts is 0!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+
+		#Process rift info
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		numpairs=0
+		for i in xrange(0,numrifts):
+			numpairs+=numpy.size(self.riftstruct[i].penaltypairs,0)
+
+		# 2 for nodes + 2 for elements+ 2 for  normals + 1 for length + 1 for fill + 1 for friction + 1 for fraction + 1 for fractionincrement + 1 for state.
+		data=numpy.zeros((numpairs,12))
+		count=0
+		for i in xrange(0,numrifts):
+			numpairsforthisrift=numpy.size(self.riftstruct[i]['penaltypairs'],0)
+			data[count:count+numpairsforthisrift-1,0:6]=self.riftstruct[i]['penaltypairs']
+			data[count:count+numpairsforthisrift-1,7]=self.riftstruct[i]['fill']
+			data[count:count+numpairsforthisrift-1,8]=self.riftstruct[i]['friction']
+			data[count:count+numpairsforthisrift-1,9]=self.riftstruct[i]['fraction']
+			data[count:count+numpairsforthisrift-1,10]=self.riftstruct[i]['fractionincrement']
+			data[count:count+numpairsforthisrift-1,11]=self.riftstruct[i]['state']
+			count+=numpairsforthisrift
+
+		WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer')
+		WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/settings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/settings.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/settings.m	(revision 13101)
@@ -43,9 +43,9 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'settings.io_gather','numel',1,'values',[0 1]);
-			md = checkfield(md,'settings.lowmem','numel',1,'values',[0 1]);
-			md = checkfield(md,'settings.results_as_patches','numel',1,'values',[0 1]);
-			md = checkfield(md,'settings.output_frequency','numel',1,'>=',1);
-			md = checkfield(md,'settings.waitonlock','numel',1);
+			md = checkfield(md,'settings.io_gather','numel',[1],'values',[0 1]);
+			md = checkfield(md,'settings.lowmem','numel',[1],'values',[0 1]);
+			md = checkfield(md,'settings.results_as_patches','numel',[1],'values',[0 1]);
+			md = checkfield(md,'settings.output_frequency','numel',[1],'>=',1);
+			md = checkfield(md,'settings.waitonlock','numel',[1]);
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/settings.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/settings.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/settings.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class settings:
+class settings(object):
+	"""
+	SETTINGS class definition
+
+	   Usage:
+	      settings=settings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,30 +26,30 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   general settings parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(obj,"io_gather","I/O gathering strategy for result outputs (default 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowmem","is the memory limited ? (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"results_as_patches","provide results as patches for each element (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
-		string="%s\n%s"%(string,fielddisplay(obj,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
+		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"results_as_patches","provide results as patches for each element (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
+		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#are we short in memory ? (0 faster but requires more memory)
-		obj.lowmem=0
+		self.lowmem=0
 
 		#i/o:
-		obj.io_gather=1
+		self.io_gather=1
 
 		#results frequency by default every step
-		obj.output_frequency=1
+		self.output_frequency=1
 
 		#do not use patches by default (difficult to plot)
-		obj.results_as_patches=0
+		self.results_as_patches=0
 
 		#this option can be activated to load automatically the results
@@ -47,7 +57,25 @@
 		#N minutes that is generated once the solution has converged
 		#0 to desactivate
-		obj.waitonlock=float('Inf')
+		self.waitonlock=float('Inf')
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'settings.io_gather','numel',[1],'values',[0,1])
+		md = checkfield(md,'settings.lowmem','numel',[1],'values',[0,1])
+		md = checkfield(md,'settings.results_as_patches','numel',[1],'values',[0,1])
+		md = checkfield(md,'settings.output_frequency','numel',[1],'>=',1)
+		md = checkfield(md,'settings.waitonlock','numel',[1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','results_as_patches','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','output_frequency','format','Integer')
+		WriteData(fid,'object',self,'fieldname','waitonlock','format','Boolean')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/solver.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/solver.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/solver.m	(revision 13101)
@@ -20,6 +20,6 @@
 		 function obj = addoptions(obj,analysis,varargin) % {{{
 		 % Usage example:
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum,stokesoptions());
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum);
+		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
 
 			 %Convert analysis from enum to string
@@ -38,8 +38,8 @@
 
 			 %MUMPS is the default solver
-			 if ismumps,
-				 obj.NoneAnalysis=mumpsoptions;
+			 if ismumps(),
+				 obj.NoneAnalysis=mumpsoptions();
 			 else
-				 obj.NoneAnalysis=iluasmoptions;
+				 obj.NoneAnalysis=iluasmoptions();
 			 end
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/solver.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/solver.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/solver.py	(revision 13101)
@@ -1,49 +1,106 @@
-#module imports {{{
-import fielddisplay 
-import ismumps
-from  mumpsoptions import *
-from  iluasmoptions import *
-#}}}
-class solver:
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		if ismumps:
-			self.options=[["NoneAnalysis",mumpsoptions()]]
+from ismumps import *
+from mumpsoptions import *
+from iluasmoptions import *
+from EnumToString import EnumToString
+from MatlabFuncs import *
+from EnumDefinitions import *
+from checkfield import *
+
+class solver(object):
+	"""
+	SOLVER class definition
+
+	   Usage:
+	      obj=solver();
+	"""
+
+	def __init__(self):    # {{{
+		#MUMPS is the default solver
+		if ismumps():
+			self.NoneAnalysis=mumpsoptions()
 		else:
-			self.options=[["NoneAnalysis",iluasmoptions()]]
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		
-		string2="   solver parameters:"
-		for i in range(len(obj.options)):
-			option=obj.options[i]
-			analysis=option[0]
-			ioptions=option[1]
+			self.NoneAnalysis=iluasmoptions()
 
-			string=""
-			for i in range(len(ioptions)):
-				option=ioptions[i]
-				if not option:
-					#do nothing
-					pass
-				elif len(option)==1:
+		#The other properties are dynamic
+	# }}}
+
+	def addoptions(self,analysis,*args):    # {{{
+		# Usage example:
+		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
+
+		#Convert analysis from enum to string
+		[analysis]=EnumToString(analysis)
+
+		#Create dynamic property if property does not exist yet
+		if not hasattr(self,analysis):
+#			exec("self.%s = None" % analysis)
+			setattr(self,analysis,None)
+
+		#Add solver options to analysis
+		if len(args)==1:
+			setattr(self,analysis,args[0])
+
+		return self
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="List of solver options per analysis:\n\n"
+		for analysis in vars(self).iterkeys():
+			s+="%s :\n" % analysis
+			s+="%s\n" % getattr(self,analysis)
+
+		return s
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		for analysis in vars(self).iterkeys():
+			if not getattr(self,analysis):
+				md.checkmessage("md.solver.%s is empty" % analysis)
+
+		return md
+	# }}}
+
+	def PetscFile(self,filename):    # {{{
+		"""
+		PETSCFILE - build petsc file
+
+		   Build a Petsc compatible options file, from the solver model field  + return options string
+
+		   Usage:     PetscFile(solver,filename);
+		"""
+
+		#open file for writing
+		try:
+			fid=open(filename,'w')
+		except IOError as e:
+			raise IOError("PetscFile error: could not open '%s' for writing." % filename)
+
+		#write header
+		fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab solver array'))
+
+		#start writing options
+		for analysis in vars(self).iterkeys():
+			options=getattr(self,analysis)
+
+			#first write analysis:
+			fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
+
+			#now, write options
+			for optionname,optionvalue in options.iteritems():
+
+				if not optionvalue:
 					#this option has only one argument
-					string="%s%s%s"%(string," -",option[0])
-				elif len(option)==2:
+					fid.write("-%s\n" % optionname)
+				else:
 					#option with value. value can be string or scalar
-					if isinstance(option[1],float):
-						string="%s%s%s%s%s"%(string," -",option[0]," ","%g"%(option[1]))
-					elif isinstance(option[1],str):
-						string="%s%s%s%s%s"%(string," -",option[0]," ",option[1])
-					elif isinstance(option[1],int):
-						string="%s%s%s%s%s"%(string," -",option[0]," ","%i"%(option[1]))
+					if   isinstance(optionvalue,(bool,int,long,float)):
+						fid.write("-%s %g\n" % (optionname,optionvalue))
+					elif isinstance(optionvalue,(str,unicode)):
+						fid.write("-%s %s\n" % (optionname,optionvalue))
 					else:
-						raise RuntimeError("%s%s%s"%("PetscString error: option #","%i"%(i)," is not well formatted"))
-				else:
-					raise RuntimeError("%s%s%s"%("PetscString error: option #","%i"%(i)," is not well formatted"))
+						raise TypeError("PetscFile error: option '%s' is not well formatted." % optionname)
 
-			string2="%s\n%s"%(string2,"   %s -> '%s'"%(analysis,string))
-		return string2
-	#}}}
+		fid.close()
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 13101)
@@ -29,5 +29,5 @@
 
 			%Early return
-			if solution~=SteadystateSolutionEnum, return; end;
+			if solution~=SteadystateSolutionEnum(), return; end;
 
 			if md.timestepping.time_step~=0,
Index: /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.py	(revision 13101)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class steadystate:
+class steadystate(object):
+	"""
+	STEADYSTATE class definition
+
+	   Usage:
+	      steadystate=steadystate();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,23 +25,44 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   steadystate solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'reltol','relative tolerance criterion'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','additional requested outputs'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','relative tolerance criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional requested outputs'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#maximum of steady state iterations
-		obj.maxiter=100
+		self.maxiter=100
 
 		#Relative tolerance for the steadystate convertgence
-		obj.reltol=0.01
+		self.reltol=0.01
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==SteadystateSolutionEnum():
+			return md
+
+		if not md.timestepping.time_step==0:
+			md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
+
+		if numpy.isnan(md.diagnostic.reltol):
+			md.checkmessage("for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 13101)
@@ -11,5 +11,5 @@
 		issmbgradients = 0;
 		isdelta18o = 0;
-	   hc = NaN;
+		hc = NaN;
 		smb_pos_max = NaN;
 		smb_pos_min = NaN;
@@ -44,31 +44,31 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum,analyses),
-				md = checkfield(md,'surfaceforcings.ispdd','numel',1,'values',[0 1]);
-				checkfield(md,'surfaceforcings.issmbgradients','numel',1,'values',[0 1]);
+			if ismember(PrognosticAnalysisEnum(),analyses),
+				md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0 1]);
+				md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0 1]);
 				if(obj.ispdd)
-				        if(obj.isdelta18o==0)
-				        	md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
-				        	md = checkfield(md,'surfaceforcings.precipitation','forcing',1,'NaN',1);
-			                else
-				                md = checkfield(md,'surfaceforcings.delta18o','NaN',1);
-				        	md = checkfield(md,'surfaceforcings.delta18o_surface','NaN',1);
-				        	md = checkfield(md,'surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
-				        	md = checkfield(md,'surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
-				        	md = checkfield(md,'surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
-				        end
+					if(obj.isdelta18o==0)
+						md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
+						md = checkfield(md,'surfaceforcings.precipitation','forcing',1,'NaN',1);
+					else
+						md = checkfield(md,'surfaceforcings.delta18o','NaN',1);
+						md = checkfield(md,'surfaceforcings.delta18o_surface','NaN',1);
+						md = checkfield(md,'surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+						md = checkfield(md,'surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+						md = checkfield(md,'surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					end
 				elseif(obj.issmbgradients)
-					checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1);
-					checkfield(md,'surfaceforcings.b_neg','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.b_neg','forcing',1,'NaN',1);
 				else
 					md = checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1);
 				end
 			end
-			if ismember(BalancethicknessAnalysisEnum,analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
 			end
@@ -103,14 +103,14 @@
 			WriteData(fid,'object',obj,'fieldname','isdelta18o','format','Boolean');
 			if obj.ispdd,
-			  if obj.isdelta18o
-			        WriteData(fid,'object',obj,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
-			        WriteData(fid,'object',obj,'fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
-			        WriteData(fid,'object',obj,'fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
-			        WriteData(fid,'object',obj,'fieldname','delta18o_surface','format','DoubleMat','mattype',1);
-			        WriteData(fid,'object',obj,'fieldname','delta18o','format','DoubleMat','mattype',1);
-			  else
-				WriteData(fid,'object',obj,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1);
-			  end
+				if obj.isdelta18o
+					WriteData(fid,'object',obj,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','delta18o_surface','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','delta18o','format','DoubleMat','mattype',1);
+				else
+					WriteData(fid,'object',obj,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1);
+				end
 			end
 			WriteData(fid,'object',obj,'fieldname','issmbgradients','format','Boolean');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class surfaceforcings:
+class surfaceforcings(object):
+	"""
+	SURFACEFORCING Class definition
+
+	   Usage:
+	      surfaceforcings=surfaceforcings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -8,4 +18,20 @@
 		self.precipitation = float('NaN')
 		self.mass_balance  = float('NaN')
+		self.ispdd = 0
+		self.issmbgradients = 0
+		self.isdelta18o = 0
+		self.hc = float('NaN')
+		self.smb_pos_max = float('NaN')
+		self.smb_pos_min = float('NaN')
+		self.a_pos = float('NaN')
+		self.b_pos = float('NaN')
+		self.a_neg = float('NaN')
+		self.b_neg = float('NaN')
+		self.monthlytemperatures = float('NaN')
+		self.delta18o = float('NaN')
+		self.delta18o_surface = float('NaN')
+		self.temperatures_presentday = float('NaN')
+		self.temperatures_lgm = float('NaN')
+		self.precipitations_presentday = float('NaN')
 
 		#set defaults
@@ -13,17 +39,101 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   surface forcings parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'ispdd','is pdd activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [Kelvin], required if pdd is activated and delta18o not activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'a_pos',' intercept of hs - smb regression line for accumulation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'a_neg',' intercept of hs - smb regression line for ablation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		  
+		#pdd method not used in default mode
+		self.ispdd=0
+		self.issmbgradients=0
+		self.isdelta18o=0
+
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if PrognosticAnalysisEnum() in analyses:
+			md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0,1])
+			md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0,1])
+			if   self.ispdd:
+				if not self.isdelta18o:
+					md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1)
+					md = checkfield(md,'surfaceforcings.precipitation','forcing',1,'NaN',1)
+				else:
+					md = checkfield(md,'surfaceforcings.delta18o','NaN',1)
+					md = checkfield(md,'surfaceforcings.delta18o_surface','NaN',1)
+					md = checkfield(md,'surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+					md = checkfield(md,'surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+					md = checkfield(md,'surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+			elif self.issmbgradients:
+				md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.b_neg','forcing',1,'NaN',1)
+			else:
+				md = checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','mass_balance','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','ispdd','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdelta18o','format','Boolean')
+
+		if self.ispdd:
+			if self.isdelta18o:
+				WriteData(fid,'object',self,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','temperatures_lgm','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','precipitations_presentday','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','delta18o_surface','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','delta18o','format','DoubleMat','mattype',1)
+			else:
+				WriteData(fid,'object',self,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
+
+		WriteData(fid,'object',self,'fieldname','issmbgradients','format','Boolean')
+
+		if self.issmbgradients:
+			WriteData(fid,'object',self,'fieldname','hc','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','smb_pos_max','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','smb_pos_min','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','a_pos','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','b_pos','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','a_neg','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','b_neg','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m	(revision 13101)
@@ -43,11 +43,11 @@
 
 			%Early return
-			if (~ismember(ThermalAnalysisEnum,analyses) & ~ismember(EnthalpyAnalysisEnum,analyses)) | (solution==TransientSolutionEnum & md.transient.isthermal==0), return; end
+			if (~ismember(ThermalAnalysisEnum(),analyses) & ~ismember(EnthalpyAnalysisEnum(),analyses)) | (solution==TransientSolutionEnum() & md.transient.isthermal==0), return; end
 
-			md = checkfield(md,'thermal.stabilization','numel',1,'values',[0 1 2]);
+			md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0 1 2]);
 			md = checkfield(md,'thermal.spctemperature','forcing',1);
-			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy & md.mesh.dimension==3),
-			md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message','spctemperature should be below the adjusted melting point');
-			md = checkfield(md,'thermal.isenthalpy','numel',1,'values',[0 1]);
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy & md.mesh.dimension==3),
+				md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message','spctemperature should be below the adjusted melting point');
+				md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0 1]);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/thermal.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/thermal.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/thermal.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class thermal:
+class thermal(object):
+	"""
+	THERMAL class definition
+
+	   Usage:
+	      thermal=thermal();
+	"""
+
 	#properties
 	def __init__(self):
@@ -18,35 +28,60 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   Thermal solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of non linear iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of non linear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Number of unstable constraints acceptable
-		obj.penalty_threshold=0
+		self.penalty_threshold=0
 
 		#Type of stabilization used
-		obj.stabilization=1
+		self.stabilization=1
 
 		#Maximum number of iterations
-		obj.maxiter=100
+		self.maxiter=100
 
 		#factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#Should we use cold ice (default) or enthalpy formulation
-		obj.isenthalpy=0
+		self.isenthalpy=0
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (ThermalAnalysisEnum() not in analyses and EnthalpyAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			return md
+
+		md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'thermal.spctemperature','forcing',1)
+		if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension==3:
+			md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message',"spctemperature should be below the adjusted melting point")
+			md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0,1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 13101)
@@ -35,9 +35,9 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'timestepping.start_time','numel',1,'NaN',1);
-			md = checkfield(md,'timestepping.final_time','numel',1,'NaN',1);
-			md = checkfield(md,'timestepping.time_step','numel',1,'>=',0,'NaN',1);
-			md = checkfield(md,'timestepping.time_adapt','numel',1,'values',[0 1]);
-			md = checkfield(md,'timestepping.cfl_coefficient','numel',1,'>',0,'<=',1);
+			md = checkfield(md,'timestepping.start_time','numel',[1],'NaN',1);
+			md = checkfield(md,'timestepping.final_time','numel',[1],'NaN',1);
+			md = checkfield(md,'timestepping.time_step','numel',[1],'>=',0,'NaN',1);
+			md = checkfield(md,'timestepping.time_adapt','numel',[1],'values',[0 1]);
+			md = checkfield(md,'timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
 			if obj.final_time-obj.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.py	(revision 13101)
@@ -1,11 +1,22 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class timestepping:
+class timestepping(object):
+	"""
+	TIMESTEPPING Class definition
+
+	   Usage:
+	      timestepping=timestepping();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
+		self.start_time      = 0
+		self.final_time      = 0
 		self.time_step       = 0
-		self.final_time      = 0
 		self.time_adapt      = 0
 		self.cfl_coefficient = 0
@@ -15,27 +26,50 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   timestepping parameters:"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"time_step","length of time steps [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"final_time","final time to stop the simulation [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
-		string="%s\n%s"%(string,fielddisplay(obj,"cfl_coefficient","coefficient applied to cfl condition"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
+		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#time between 2 time steps
-		obj.time_step=1/2
+		self.time_step=1/2
 
 		#final time
-		obj.final_time=10*obj.time_step
+		self.final_time=10*self.time_step
 
 		#time adaptation? 
-		obj.time_adapt=0
-		obj.cfl_coefficient=.5
+		self.time_adapt=0
+		self.cfl_coefficient=.5
 
-		return obj
+		return self
 	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'timestepping.start_time','numel',[1],'NaN',1)
+		md = checkfield(md,'timestepping.final_time','numel',[1],'NaN',1)
+		md = checkfield(md,'timestepping.time_step','numel',[1],'>=',0,'NaN',1)
+		md = checkfield(md,'timestepping.time_adapt','numel',[1],'values',[0,1])
+		md = checkfield(md,'timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)
+		if self.final_time-self.start_time<0:
+			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','start_time','format','Double')
+		WriteData(fid,'object',self,'fieldname','final_time','format','Double')
+		WriteData(fid,'object',self,'fieldname','time_step','format','Double')
+		WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/transient.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/transient.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/transient.m	(revision 13101)
@@ -33,10 +33,10 @@
 
 			%Early return
-			if solution~=TransientSolutionEnum, return; end
+			if solution~=TransientSolutionEnum(), return; end
 
-			md = checkfield(md,'transient.isprognostic','numel',1,'values',[0 1]);
-			md = checkfield(md,'transient.isdiagnostic','numel',1,'values',[0 1]);
-			md = checkfield(md,'transient.isthermal','numel',1,'values',[0 1]);
-			md = checkfield(md,'transient.isgroundingline','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.isprognostic','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.isdiagnostic','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.isthermal','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.requested_outputs','size',[NaN 1]);
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/transient.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/transient.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/transient.py	(revision 13101)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class transient:
+class transient(object):
+	"""
+	TRANSIENT class definition
+
+	   Usage:
+	      transient=transient();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,25 +26,49 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   transient solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'isprognostic','indicates if a prognostic solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isthermal','indicates if a thermal solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isdiagnostic','indicates if a diagnostic solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isgroundingline','indicates if a groundingline migration is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','list of additional outputs requested'))
+		string="%s\n%s"%(string,fielddisplay(self,'isprognostic','indicates if a prognostic solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isthermal','indicates if a thermal solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdiagnostic','indicates if a diagnostic solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
-		obj.isprognostic=1
-		obj.isdiagnostic=1
-		obj.isthermal=1
-		obj.isgroundingline=0
+		self.isprognostic=1
+		self.isdiagnostic=1
+		self.isthermal=1
+		self.isgroundingline=0
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==TransientSolutionEnum():
+			return md
+
+		md = checkfield(md,'transient.isprognostic','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isdiagnostic','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isthermal','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.requested_outputs','size',[float('NaN')])
+
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isprognostic','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdiagnostic','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m	(revision 13101)
@@ -120,5 +120,5 @@
 		%}}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum,'format','Integer');
+			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/verbose.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/verbose.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/verbose.py	(revision 13101)
@@ -1,6 +1,6 @@
 from pairoptions import *
 from MatlabFuncs import *
+from EnumDefinitions import *
 from WriteData import *
-from EnumDefinitions import *
 
 class verbose(object):
@@ -44,5 +44,5 @@
 		elif len(args) == 1:
 			binary=args[0]
-			if   isinstance(binary,str):
+			if   isinstance(binary,(str,unicode)):
 				if strcmpi(binary,'all'):
 					binary=2**11-1    #all ones
@@ -52,5 +52,5 @@
 					binary=int(binary,2)
 					self.BinaryToVerbose(binary)
-			elif isinstance(binary,(int,float)):
+			elif isinstance(binary,(int,long,float)):
 				self.BinaryToVerbose(int(binary))
 
@@ -62,5 +62,5 @@
 			listproperties=vars(self)
 			for [fieldname,fieldvalue] in listproperties.iteritems():
-				if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,float)):
+				if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,long,float)):
 					setattr(self,fieldname,bool(fieldvalue))
 				else:
@@ -125,5 +125,5 @@
 
 	def marshall(self,fid):    # {{{
-			WriteData(fid,'data',VerboseToBinary(self),'enum',VerboseEnum,'format','Integer')
+			WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
 	# }}}
 
Index: /issm/branches/trunk-jpl-damage/src/m/consistency/QueueRequirements.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/consistency/QueueRequirements.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/consistency/QueueRequirements.m	(revision 13101)
@@ -0,0 +1,35 @@
+function QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,queue,np,time)
+%QUEUEREQUIREMENTS - queue requirements in time, number of cpus, by name of queue.
+%
+%   Usage: 
+%      QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,np,time)
+
+%Ok, go through requirements for current queue:
+index=ismemberi(queue,available_queues);
+if  ~index,
+	%ok, either we a generic cluster, with 'none' queue, or we could not find the queue reqruirements
+	if strcmpi(available_queues{1},'none'),
+		%reset index to 1, so we can fish the requirements
+		index=1;
+	else
+		string=available_queues{1};
+		for i=2:length(available_queues),
+			string=[string ' ' available_queues{i}];
+		end
+		error(['QueueRequirements error message: availables queues are ' string]);
+	end
+end
+
+%check on time requirements
+rtime=queue_requirements_time(index);
+if time<=0,
+	error('QueueRequirements: time should be a positive number');
+end
+if time>rtime,
+	error(['QueueRequirements: time should be < ' num2str(rtime) ' for queue: ' queue]);
+end
+
+%check on np requirements
+if np<=0,
+	error('QueueRequirements: np should be a positive number');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.m	(revision 13101)
@@ -0,0 +1,195 @@
+function md = checkfield(md,fieldname,varargin)
+%CHECKFIELD - check field consistency
+%
+%   Used to check model consistency.
+%   Available options:
+%      - NaN: 1 if check that there is no NaN
+%      - size: [lines cols], NaN for non checked dimensions
+%      - >:  greater than provided value
+%      - >=: greater or equal to provided value
+%      - <:  smallerthan provided value
+%      - <=: smaller or equal to provided value
+%      - < vec:  smallerthan provided values on each vertex
+%      - forcing: 1 if check forcing consistency (size and time)
+%      - values: cell of strings or vector of acceptable values
+%      - numel: list of acceptable number of elements
+%      - cell: 1 if check that is cell
+%      - empty: 1 if check that non empty
+%      - message: overloaded error message
+%
+%   Usage:
+%      md = checkfield(md,fieldname,options);
+%
+%   Example:
+%      md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+%      md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+%      md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+
+%get options
+options=pairoptions(varargin{:});
+
+%get field from model
+eval(['field=md.' fieldname ';']);
+
+%check empty
+if exist(options,'empty')
+	if isempty(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' is empty']));
+	end
+end
+
+%Check size
+if exist(options,'size')
+	fieldsize=getfieldvalue(options,'size');
+	if isnan(fieldsize(1)),
+		if (size(field,2)~=fieldsize(2)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(2)) ' columns']));
+		end
+	elseif isnan(fieldsize(2)),
+		if (size(field,1)~=fieldsize(1)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(1)) ' lines']));
+		end
+	else
+		if ((size(field,1)~=fieldsize(1)) |  (size(field,2)~=fieldsize(2)))
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldsize(1)) ' x ' num2str(fieldsize(2))]));
+		end
+	end
+end
+
+%Check numel
+if exist(options,'numel')
+	fieldnumel=getfieldvalue(options,'numel');
+	if ~ismember(numel(field),fieldnumel),
+		if length(fieldnumel)==1
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g ',fieldnumel) ]));
+		elseif length(fieldnumel)==2
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldnumel(1)) ' or ' num2str(fieldnumel(2)) ]));
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g, ',fieldnumel(1:end-1)) ' or ' num2str(fieldnumel(end)) ]));
+		end
+	end
+end
+
+%check NaN
+if getfieldvalue(options,'NaN',0);
+	field2=reshape(field,prod(size(field)),1);
+	if any(isnan(field2)),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['NaN values found in field ''' fieldname '''']));
+	end
+end
+
+%check cell
+if getfieldvalue(options,'cell',0);
+	if ~iscell(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should be a cell']));
+	end
+end
+
+%check values
+if exist(options,'values')
+	fieldvalues=getfieldvalue(options,'values');
+	if iscell(fieldvalues), %strings
+		if ischar(field) | iscell(fieldvalues),
+			if any(~ismember(field,fieldvalues)),
+				if length(fieldvalues)==1
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' value should be ''' fieldvalues{1} '''']));
+				elseif length(fieldvalues)==2
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' values should be ''' fieldvalues{1} ''' or ''' fieldvalues{2} '''']));
+				else
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' should have values in ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+				end
+			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be one of the following strings: ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+		end
+	else
+		field2=reshape(field,prod(size(field)),1);
+		if isnumeric(field),
+			if any(~ismember(field2,fieldvalues)),
+				md = checkmessage(md,getfieldvalue(options,'message',...
+					['field ''' fieldname ''' should have values in [' num2str(fieldvalues) ']']));
+			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be a number in [' num2str(fieldvalues) ']']));
+		end
+	end
+end
+
+%check greater
+if exist(options,'>=')
+	lowerbound=getfieldvalue(options,'>=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+if exist(options,'>')
+	lowerbound=getfieldvalue(options,'>');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<=lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+
+%check smaller
+if exist(options,'<=')
+	upperbound=getfieldvalue(options,'<=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+if exist(options,'<')
+	upperbound=getfieldvalue(options,'<');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>=upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+
+%check file
+if getfieldvalue(options,'file',0),
+	if ~exist(field,'file')
+		md = checkmessage(md,['file provided in ''' fieldname ''': ''' field ''' does not exist']);
+	end
+end
+
+%Check forcings (size and times)
+if getfieldvalue(options,'forcing',0),
+	if size(field,1)==md.mesh.numberofvertices,
+		if ~size(field,2)==1,
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have only one column as there are md.mesh.numberofvertices lines']));
+		end
+	elseif size(field,1)==md.mesh.numberofvertices+1
+		if any(field(end,:)~=sort(field(end,:))),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns should be sorted chronologically']));
+		end
+		if any(field(end,1:end-1)==field(end,2:end)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
+		end
+	else
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines']));
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/consistency/checkfield.py	(revision 13101)
@@ -0,0 +1,160 @@
+import numpy
+import os
+from pairoptions import *
+from MatlabFuncs import *
+
+def checkfield(md,fieldname,*args):
+	"""
+	CHECKFIELD - check field consistency
+
+	   Used to check model consistency.
+	   Available options:
+	      - NaN: 1 if check that there is no NaN
+	      - size: [lines cols], NaN for non checked dimensions
+	      - >:  greater than provided value
+	      - >=: greater or equal to provided value
+	      - <:  smallerthan provided value
+	      - <=: smaller or equal to provided value
+	      - < vec:  smallerthan provided values on each vertex
+	      - forcing: 1 if check forcing consistency (size and time)
+	      - values: cell of strings or vector of acceptable values
+	      - numel: list of acceptable number of elements
+	      - cell: 1 if check that is cell
+	      - empty: 1 if check that non empty
+	      - message: overloaded error message
+
+	   Usage:
+	      md = checkfield(md,fieldname,options);
+
+	   Example:
+	      md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+	      md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+	      md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+	"""
+
+	#get options
+	options=pairoptions(*args)
+
+	#get field from model
+#	field=getattr(md,fieldname)
+	exec("field=md.%s" % fieldname)
+	if isinstance(field,(bool,int,long,float)):
+		field=numpy.array([field])
+
+	#check empty
+	if options.exist('empty'):
+		if not field:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' is empty" % fieldname))
+
+	#Check size
+	if options.exist('size'):
+		fieldsize=options.getfieldvalue('size')
+		if   len(fieldsize) == 1:
+			if   numpy.isnan(fieldsize[0]):
+				pass
+			elif not numpy.size(field,0)==fieldsize[0]:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldsize[0])))
+		elif len(fieldsize) == 2:
+			if   numpy.isnan(fieldsize[0]):
+				if not numpy.size(field,1)==fieldsize[1]:
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' should have %d columns" % (fieldname,fieldsize[1])))
+			elif numpy.isnan(fieldsize[1]):
+				if not numpy.size(field,0)==fieldsize[0]:
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' should have %d lines" % (fieldname,fieldsize[0])))
+			else:
+				if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
+	
+	#Check numel
+	if options.exist('numel'):
+		fieldnumel=options.getfieldvalue('numel')
+		if numpy.size(field) not in fieldnumel:
+			if   len(fieldnumel)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldnumel)))
+			elif len(fieldnumel)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d or %d" % (fieldname,fieldnumel[0],fieldnumel[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %s" % (fieldname,fieldnumel)))
+
+	#check NaN
+	if options.getfieldvalue('NaN',0):
+		if numpy.any(numpy.isnan(field)):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"NaN values found in field '%s'" % fieldname))
+
+	#check cell
+	if options.getfieldvalue('cell',0):
+		if not isinstance(field,(tuple,list,dict)):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should be a cell" % fieldname))
+
+	#check values
+	if options.exist('values'):
+		fieldvalues=options.getfieldvalue('values')
+		if False in ismember(field,fieldvalues):
+			if   len(fieldvalues)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' value should be '%s'"  % (fieldname,fieldvalues[0])))
+			elif len(fieldvalues)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' values should be '%s' or '%s'"  % (fieldname,fieldvalues[0],fieldvalues[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have values in %s" % (fieldname,fieldvalues)))
+
+	#check greater
+	if options.exist('>='):
+		lowerbound=options.getfieldvalue('>=')
+		if numpy.any(field<lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+	if options.exist('>'):
+		lowerbound=options.getfieldvalue('>')
+		if numpy.any(field<=lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+
+	#check smaller
+	if options.exist('<='):
+		upperbound=options.getfieldvalue('<=')
+		if numpy.any(field>upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+	if options.exist('<'):
+		upperbound=options.getfieldvalue('<')
+		if numpy.any(field>=upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+
+	#check file
+	if options.getfieldvalue('file',0):
+		if not os.path.exists(field):
+			md = md.checkmessage("file provided in '%s': '%s' does not exist" % (fieldname,field))
+
+	#Check forcings (size and times)
+	if options.getfieldvalue('forcing',0):
+		if   numpy.size(field,0)==md.mesh.numberofvertices:
+			if len(numpy.shape(field))>1 and not numpy.size(field,1)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname))
+		elif numpy.size(field,0)==md.mesh.numberofvertices+1:
+			if not all(field[-1,:]==numpy.sort(field[-1,:])):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns should be sorted chronologically" % fieldname))
+			if any(field[-1,0:-1]==field[-1,1:]):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns must not contain duplicate timesteps" % fieldname))
+		else:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines" % fieldname))
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.m	(revision 13101)
@@ -0,0 +1,101 @@
+function ismodelselfconsistent(md),
+%ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+%
+%   Usage:
+%      ismodelselfconsistent(md),
+
+%initialize consistency as true
+md.private.isconsistent=true;
+
+%Get solution and associated analyses
+solution=md.private.solution;
+[analyses,numanalyses]=AnalysisConfiguration(solution);
+
+%Go through a model field, check that it is a class, and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be checked
+	if ismember(field,{'results' 'debug' 'radaroverlay'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		md=checkmessage(md,['field ''' char(field) ''' is not an object']);
+	end
+
+	%Check consistency of the object
+	if verLessThan('matlab', '7.6')
+		md=checkconsistency(md.(field),md,solution,analyses);
+	else
+		md=md.(field).checkconsistency(md,solution,analyses);
+	end
+end
+
+%error message if mode is not consistent
+if md.private.isconsistent==false,
+	error('Model not consistent, see messages above');
+end
+end
+
+function [analyses,numanalyses]=AnalysisConfiguration(solutiontype), % {{{
+%ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+%
+%   Usage:
+%      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+
+
+
+switch solutiontype,
+
+	case DiagnosticSolutionEnum(),
+		numanalyses=5;
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum()];
+
+	case SteadystateSolutionEnum(),
+		numanalyses=7; 
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case ThermalSolutionEnum(),
+		numanalyses=2; 
+		analyses=[ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case EnthalpySolutionEnum(),
+		numanalyses=1; 
+		analyses=[EnthalpyAnalysisEnum()];
+
+	case PrognosticSolutionEnum(),
+		numanalyses=1; 
+		analyses=[PrognosticAnalysisEnum()];
+
+	case BalancethicknessSolutionEnum(),
+		numanalyses=1; 
+		analyses=[BalancethicknessAnalysisEnum()];
+
+	case SurfaceSlopeSolutionEnum(),
+		numanalyses=1; 
+		analyses=[SurfaceSlopeAnalysisEnum()];
+
+	case BedSlopeSolutionEnum(),
+		numanalyses=1; 
+		analyses=[BedSlopeAnalysisEnum()];
+
+	case TransientSolutionEnum(),
+		numanalyses=9; 
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();PrognosticAnalysisEnum()];
+
+	case FlaimSolutionEnum(),
+		numanalyses=1; 
+		analyses=[FlaimAnalysisEnum()];
+
+	case HydrologySolutionEnum(),
+		numanalyses=3; 
+		analyses=[BedSlopeAnalysisEnum();SurfaceSlopeAnalysisEnum();HydrologyAnalysisEnum()];
+
+	otherwise
+		error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+	end
+end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/consistency/ismodelselfconsistent.py	(revision 13101)
@@ -0,0 +1,95 @@
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def AnalysisConfiguration(solutiontype): #{{{
+	"""
+	ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+
+		Usage:
+			[analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+	"""
+
+	if   solutiontype == DiagnosticSolutionEnum():
+		numanalyses=5
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum()]
+
+	elif solutiontype == SteadystateSolutionEnum():
+		numanalyses=7 
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == ThermalSolutionEnum():
+		numanalyses=2 
+		analyses=[ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == EnthalpySolutionEnum():
+		numanalyses=1 
+		analyses=[EnthalpyAnalysisEnum()]
+
+	elif solutiontype == PrognosticSolutionEnum():
+		numanalyses=1 
+		analyses=[PrognosticAnalysisEnum()]
+
+	elif solutiontype == BalancethicknessSolutionEnum():
+		numanalyses=1 
+		analyses=[BalancethicknessAnalysisEnum()]
+
+	elif solutiontype == SurfaceSlopeSolutionEnum():
+		numanalyses=1 
+		analyses=[SurfaceSlopeAnalysisEnum()]
+
+	elif solutiontype == BedSlopeSolutionEnum():
+		numanalyses=1 
+		analyses=[BedSlopeAnalysisEnum()]
+
+	elif solutiontype == TransientSolutionEnum():
+		numanalyses=9 
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),PrognosticAnalysisEnum()]
+
+	elif solutiontype == FlaimSolutionEnum():
+		numanalyses=1 
+		analyses=[FlaimAnalysisEnum()]
+
+	elif solutiontype == HydrologySolutionEnum():
+		numanalyses=3 
+		analyses=[BedSlopeAnalysisEnum(),SurfaceSlopeAnalysisEnum(),HydrologyAnalysisEnum()]
+
+	else:
+		raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])
+
+	return analyses,numanalyses
+#}}}
+
+def ismodelselfconsistent(md):
+	"""
+	ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+
+	   Usage:
+	      ismodelselfconsistent(md),
+	"""
+
+	#initialize consistency as true
+	md.private.isconsistent=True
+
+	#Get solution and associated analyses
+	solution=md.private.solution
+	analyses,numanalyses=AnalysisConfiguration(solution)
+
+	#Go through a model fields, check that it is a class, and call checkconsistency
+	fields=vars(md)
+	for field in fields.iterkeys():
+
+		#Some properties do not need to be checked
+		if field in ['results','debug','radaroverlay']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'checkconsistency'):
+			md.checkmessage("field '%s' is not an object." % field)
+
+		#Check consistency of the object
+		exec("md.%s.checkconsistency(md,solution,analyses)" % field)
+
+	#error message if mode is not consistent
+	if not md.private.isconsistent:
+		raise RuntimeError('Model not consistent, see messages above.')
+
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCall.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCall.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCall.m	(revision 13101)
@@ -0,0 +1,84 @@
+function md=BamgCall(md,field,hmin,hmax,gradation,epsilon),
+%BAMGCALL - call bam
+%
+%   build a metric using the Hessian of the given field
+%   call Bamg and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=BamgCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=BamgCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCallFromMetric.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 13101)
@@ -0,0 +1,65 @@
+function md=BamgCallFromMetric(md,metric,gradation),
+%BAMGCALL - call bam
+%
+%   call Bamg and the output mesh is plugged onto the model
+%   -gradation = maximum edge length gradation between 2 elements
+%
+%   Usage:
+%      md=BamgCallFromMetric(md,metric,gradation);
+%
+%   Example:
+%      md=BamgCall(md,metric,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/YamsCall.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/YamsCall.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/YamsCall.m	(revision 13101)
@@ -0,0 +1,104 @@
+function md=YamsCall(md,field,hmin,hmax,gradation,epsilon),
+%YAMSCALL - call yams
+%
+%   build a metric using the Hessian of the given field
+%   call Yams and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=YamsCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=YamsCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.mask.vertexonwater)==md.mesh.numberofvertices,
+	pos=find(md.mask.vertexonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+save -ascii carre0.met  metric
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'\n%s\n%i\n','MeshVersionFormatted',1);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y zeros(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements zeros(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+	
+%Deal with rifts
+if ~isnan(md.rifts.riftstruct),
+	
+	%we have the list of triangles that make up the rift. keep those triangles around during refinement.
+	triangles=[];
+	for i=1:size(md.rifts.riftstruct,1),
+		triangles=[triangles md.rifts(i).segments(:,3)'];
+	end
+
+	fprintf(fid,'\n\n%s\n%i\n\n','RequiredTriangles',length(triangles));
+	fprintf(fid,'%i\n',triangles);
+end
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call yams
+fprintf('%s\n','      call Yams...');
+if ispc
+	%windows
+	system(['yams2-win -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+elseif ismac
+	%Macosx
+	system(['yams2-osx -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+else
+	%Linux
+	system(['yams2-linux -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+end
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+Tria=load('carre1.tria');
+Coor=load('carre1.coor');
+md.mesh.x=Coor(:,1);
+md.mesh.y=Coor(:,2);
+md.mesh.z=zeros(size(Coor,1),1);
+md.mesh.elements=Tria;
+md.mesh.numberofvertices=size(Coor,1);
+md.mesh.numberofelements=size(Tria,1);
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.tria carre1.coor carre1.meshb');
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/meshread.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/meshread.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/meshread.m	(revision 13101)
@@ -0,0 +1,41 @@
+function Struct=meshread(filename);
+
+%some checks
+if ~exist(filename),
+	error(['meshread error message: file ' filename ' not found!']);
+end
+
+fid=fopen(filename,'r');
+
+while (~feof(fid)),
+
+	A=fscanf(fid,'%s',1);
+
+	if strcmp(A,'MeshVersionFormatted');
+		Struct.Version=fscanf(fid,'%s',1);
+
+	elseif strcmp(A,'Dimension'),
+		Struct.Dimension=fscanf(fid,'%i',1);
+
+	elseif strcmp(A,'Vertices'),
+		Struct.nods=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%f %f %f',[3 Struct.nods]);
+		Struct.x=A(1,:)';
+		Struct.y=A(2,:)';
+
+	elseif strcmp(A,'Triangles'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i',[4 Struct.nels]);
+		Struct.index=A(1:3,:)';
+
+	elseif strcmp(A,'Quadrilaterals'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i %i',[5 Struct.nels]);
+		Struct.index=A(1:4,:)';
+	else
+		%do nothing
+
+	end
+end
+
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/yams.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/yams.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/bamg/yams.m	(revision 13101)
@@ -0,0 +1,171 @@
+function md=yams(md,varargin);
+%MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
+%
+%   Usage:
+%      md=yams(md,varargin);
+%      where varargin is a lit of paired arguments. 
+%      arguments can be: 'domainoutline': Argus file containing the outline of the domain to be meshed
+%      arguments can be: 'velocities': matlab file containing the velocities [m/yr]
+%      optional arguments: 'groundeddomain': Argus file containing the outline of the grounded ice
+%                          this option is used to minimize the metric on water (no refinement)
+%      optional arguments: 'resolution': initial mesh resolution [m]
+%      optional arguments: 'nsteps': number of steps of mesh adaptation
+%      optional arguments: 'epsilon': average interpolation error wished [m/yr]
+%      optional arguments: 'hmin': minimum edge length
+%      optional arguments: 'hmanx': maximum edge
+%      optional arguments: 'riftoutline': if rifts are present, specifies rift outline file.
+%      
+%
+%   Examples:
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp','nsteps',6,'epsilon',2,'hmin',500,'hmax',30000);
+
+%recover options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%recover some fields
+disp('MeshYams Options:')
+domainoutline=getfieldvalue(options,'domainoutline');
+disp(sprintf('   %-15s: ''%s''','DomainOutline',domainoutline));
+riftoutline=getfieldvalue(options,'riftoutline','N/A');
+disp(sprintf('   %-15s: ''%s''','riftoutline',riftoutline));
+groundeddomain=getfieldvalue(options,'groundeddomain','N/A');
+disp(sprintf('   %-15s: ''%s''','GroundedDomain',groundeddomain));
+velocities=getfieldvalue(options,'velocities');
+disp(sprintf('   %-15s: ''%s''','Velocities',velocities));
+resolution=getfieldvalue(options,'resolution',5000);
+disp(sprintf('   %-15s: %f','Resolution',resolution));
+nsteps=getfieldvalue(options,'nsteps',6);
+disp(sprintf('   %-15s: %i','nsteps',nsteps));
+gradation=getfieldvalue(options,'gradation',2*ones(nsteps,1));
+disp(sprintf('   %-15s: %g','gradation',gradation(1)));
+epsilon=getfieldvalue(options,'epsilon',3);
+disp(sprintf('   %-15s: %f','epsilon',epsilon));
+hmin=getfieldvalue(options,'hmin',500);
+disp(sprintf('   %-15s: %f','hmin',hmin));
+hmax=getfieldvalue(options,'hmax',150*10^3);
+disp(sprintf('   %-15s: %f\n','hmax',hmax));
+
+%mesh with initial resolution
+disp('Initial mesh generation...');
+if strcmpi(riftoutline,'N/A');
+	md=setmesh(md,domainoutline,resolution);
+else
+	md=setmesh(md,domainoutline,riftoutline,resolution);
+	md=meshprocessrifts(md,domainoutline);
+end
+disp(['Initial mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%load velocities 
+disp('loading velocities...');
+Names=VelFindVarNames(velocities);
+Vel=load(velocities);
+
+%start mesh adaptation
+for i=1:nsteps,
+	disp(['Iteration #' num2str(i) '/' num2str(nsteps)]);
+
+	%interpolate velocities onto mesh
+	disp('   interpolating velocities...');
+	if strcmpi(Names.interp,'node'),
+		vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	else
+		vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	end
+	field=sqrt(vx_obs.^2+vy_obs.^2);
+
+	%set mask.vertexonwater  field
+	if ~strcmp(groundeddomain,'N/A'),
+		nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+		md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+		md.mask.vertexonwater(find(nodeground))=0;
+	else
+		md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+	end
+
+	%adapt according to velocities
+	disp('   adapting...');
+	md=YamsCall(md,field,hmin,hmax,gradation(i),epsilon);
+
+	%if we have rifts, we just messed them up, we need to recreate the segments that constitute those 
+	%rifts, because the segments are used in YamsCall to freeze the rifts elements during refinement.
+	if md.rifts.numrifts, 
+		md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+		md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+		md.mesh.segments=findsegments(md);
+		md=yamsrecreateriftsegments(md);
+	end
+
+end
+	
+disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%recreate segments
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Fill in rest of fields:
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+if ~strcmp(groundeddomain,'N/A'),
+	nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+	md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+	md.mask.vertexonwater(find(nodeground))=0;
+else
+	md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+end
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+end
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+
+%deal with rifts 
+if md.rifts.numrifts,
+	%first, recreate rift segments
+	md=meshyamsrecreateriftsegments(md);
+
+	%using the segments, recreate the penaltypairs
+	for j=1:md.rifts.numrifts,
+		rift=md.rifts.riftstruct(j);
+
+		%build normals and lengths of segments:
+		lengths=sqrt((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))).^2 + (md.mesh.y(rift.segments(:,1))-md.mesh.y(rift.segments(:,2))).^2 );
+		normalsx=cos(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+		normalsy=sin(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+
+		%ok, build penaltypairs: 
+		numpenaltypairs=length(rift.segments)/2-1;
+		rift.penaltypairs=zeros(numpenaltypairs,7);
+
+		for i=1:numpenaltypairs,
+			rift.penaltypairs(i,1)=rift.segments(i,2);
+			rift.penaltypairs(i,2)=rift.segments(end-i,2);
+			rift.penaltypairs(i,3)=rift.segments(i,3);
+			rift.penaltypairs(i,4)=rift.segments(end-i,3);
+			rift.penaltypairs(i,5)=normalsx(i)+normalsx(i+1);
+			rift.penaltypairs(i,6)=normalsy(i)+normalsy(i+1);
+			rift.penaltypairs(i,7)=(lengths(i)+lengths(i+1))/2;
+		end
+		%renormalize norms: 
+		norms=sqrt(rift.penaltypairs(:,5).^2+rift.penaltypairs(:,6).^2);
+		rift.penaltypairs(:,5)=rift.penaltypairs(:,5)./norms;
+		rift.penaltypairs(:,6)=rift.penaltypairs(:,6)./norms;
+
+		md.rifts.riftstruct(j)=rift;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/MeltingGroundingLines.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 13101)
@@ -0,0 +1,26 @@
+function md=MeltingGroundingLines(md,distance,value)
+%MELTINGGROUNDINGLINES - set melting near grounding lines to a constant value
+%
+%   Usage:
+%      md=MeltingGroundingLines(md,distance,value)
+%
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+
+for i=1:length(pos_shelf)
+
+	if (mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d<distance,
+
+		md.melting(pos_shelf(i))=value;
+
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/PropagateFlagsUntilDistance.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 13101)
@@ -0,0 +1,60 @@
+function new_flags=PropagateFlagsUntilDistance(md,flags,distance)
+%PROPAGATEFLAGSUNTILDISTANCE
+%
+% Usage: 
+%              flags=PropagateFlagsUntilDistance(md,flags,distance)
+%
+%
+
+new_flags=flags;
+
+%make 3d work in 2d: 
+if md.mesh.dimension==3,
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.elements=md.mesh.elements2d;
+end
+
+%find elements that are at the border of flags: 
+flag_elements=find(flags);
+conn=md.mesh.elementconnectivity(flag_elements,:);
+pos=find(conn);conn(pos)=~flags(conn(pos));
+sum_conn=sum(conn,2);
+border_elements=flag_elements(find(sum_conn>=1));
+
+%average x and y over elements: 
+x_elem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+y_elem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+
+while 1,
+
+	%keep copy of new_flags for this loop: 
+	new_flags_bak=new_flags;
+
+	%extend new flags by connectivity
+	pos=find(new_flags);
+
+	connected_elements=md.mesh.elementconnectivity(pos,:);
+	connected_elements=connected_elements(find(connected_elements));
+	new_flags(connected_elements)=1;
+
+	%get new elements: 
+	new_elements=find(new_flags & ~new_flags_bak);
+	if ~length(new_elements),
+		%we are done!
+		break;
+	end
+
+	%check which of these new elements are more than distance away from the border elements
+	for i=1:length(new_elements),
+		dist=sqrt(     (x_elem(border_elements)-x_elem(new_elements(i))).^2 + (y_elem(border_elements)-y_elem(new_elements(i))).^2)-distance;
+		if ~any(dist<0)
+			%none of the border elements are within distance, this element is outside out area of interest.
+			%ensure this element never gets found again in the connectivity.
+			pos=find(md.mesh.elementconnectivity==new_elements(i));
+			md.mesh.elementconnectivity(pos)=0;
+			%exclude this new element from the new_flags!
+			new_flags(new_elements(i))=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/ecco32issm.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/ecco32issm.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/ecco32issm.m	(revision 13101)
@@ -0,0 +1,8 @@
+function nodefield=ecco32issm(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/issm2ecco3.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/issm2ecco3.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/ecco/issm2ecco3.m	(revision 13101)
@@ -0,0 +1,8 @@
+function nodefield=issm2ecco3(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gamv.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gamv.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gamv.m	(revision 13101)
@@ -0,0 +1,70 @@
+function output = gamv(x,y,data,varargin);
+%GAMV - use gslib for Kriging
+%
+%   Usage:
+%      output = gamv(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nlag = getfieldvalue(options,'nlag', 20);
+dlag = getfieldvalue(options,'dlag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('gamv.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str(nlag,'%i')           ,'\number of lags');
+fprintf(fid,'%-30s %s\n',num2str(dlag,'%g')           ,'\lag separation distance');
+fprintf(fid,'%-30s %s\n',num2str(dlag/2,'%g')         ,'\lag tolerance');
+fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+fclose(fid);
+
+%Call gamv
+system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+delete('gamv.par');
+
+%Read output
+output   = struct('Semivariogram',[],'Covariance',[]);
+counter1 = 1;
+counter2 = 1;
+fid=fopen('gamv.out','r');
+while (~feof(fid)),
+	A=fscanf(fid,'%s',1);
+	if strcmp(A,'Covariance');
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter1).Covariance=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter1=counter1+1;
+	elseif strcmp(A,'Semivariogram'),
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter2).Semivariogram=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter2=counter2+1;
+	else
+		%do nothing
+	end
+end
+fclose(fid);
+delete('gamv.out')
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gslib.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gslib.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/gslib.m	(revision 13101)
@@ -0,0 +1,112 @@
+function output = gslib(x,y,data,varargin);
+%GSLIB - use gslib for Kriging
+%
+%   Usage:
+%      output = gslib(x,y,data,varargin)
+
+%Output Matrix
+xmin   = xl(1);
+ymin   = yl(1);
+nx     = 101;
+ny     = 101;
+deltax = 5000;
+deltay = 5000;
+
+%Variogram
+nugget=10;
+sill  =164;
+range =25763;
+
+%Kriging options
+mindata = 1;
+maxdata = 50;
+maxsearchradius = 50000;
+
+%Some intermediaries (Convert to gslib's parameters);
+c = (sill-nugget);
+a = sqrt(3)*range;
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+if 0, %GAMV
+	%Write parameter file
+	fid=fopen('gamv.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+	fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+	fprintf(fid,'%-30s %s\n','20'                         ,'\number of lags');
+	fprintf(fid,'%-30s %s\n','5.0'                        ,'\lag separation distance');
+	fprintf(fid,'%-30s %s\n','3.0'                        ,'\lag tolerance');
+	fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+	fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+	fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+	fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+	fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+	fclose(fid);
+
+	%Call gamv
+	system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+
+else, %Kriging KB2D
+	%Write parameter file
+	fid=fopen('kb2d.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for KB2D');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'                  ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 3'                          ,'\columns for X, Y and variable');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'                 ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','0'                              ,'\debugging level: 0,1,2,3');
+	fprintf(fid,'%-30s %s\n','kb2d.dbg'                       ,'\file for debuggging output');
+	fprintf(fid,'%-30s %s\n','kb2d.out'                       ,'\file for kriged output');
+	fprintf(fid,'%-30s %s\n',num2str([nx xmin deltax],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n',num2str([ny ymin deltay],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n','1 1'                            ,'\x and y block discretization');
+	fprintf(fid,'%-30s %s\n',num2str([mindata maxdata],'%6g') ,'\min and max data for kriging');
+	fprintf(fid,'%-30s %s\n',num2str(maxsearchradius,'%6g')   ,'\max search radius');
+	fprintf(fid,'%-30s %s\n','1 2.302'                        ,'\0=SK, 1=OK, (mean if SK)');
+	fprintf(fid,'%-30s %s\n',['1 ' num2str(nugget)]           ,'\nst, nugget effect');
+	fprintf(fid,'%-30s %s\n',['3 ' num2str([c 0.0 a a],'%10g')],'\it, c, azm, a_max, a_min');
+	fclose(fid);
+
+	tic;system([issmdir() '/externalpackages/gslib/install/kb2d kb2d.par']);toc;
+	delete('kb2d.par');
+
+	%Read output
+	fid=fopen('kb2d.out','r');
+	while (~feof(fid)),
+		A=fscanf(fid,'%s',1);
+		if strcmp(A,'KB2D');
+			A=fscanf(fid,'%s',1); %Read output
+			params=fscanf(fid,'%i %i %i %i %g %g %g %g %g %g %1',[11 1]);
+		elseif strcmp(A,' Estimate'),
+			continue;
+		elseif strcmp(A,'Estimation'),
+			A=fscanf(fid,'%s',1); %Read Variance
+			A=fscanf(fid,'%g %g',[params(1) params(2)*params(3)]);
+			B=A(1,:); B=reshape(B,[params(3),params(2)])';
+			E=A(2,:); E=reshape(E,[params(3),params(2)])';
+		else
+			%do nothing
+		end
+	end
+	fclose(fid);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/pkriging.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/pkriging.m	(revision 13101)
@@ -0,0 +1,55 @@
+function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+%PKRIGING - parallel Kriging
+%
+%   Usage:
+%      [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+
+options=pairoptions(varargin{:});
+cluster=getfieldvalue(options,'cluster',generic('np',10));
+options=removefield(options,'cluster',0);
+name   = ['krig' num2str(feature('GetPid'))];
+
+% =========================================   MARSHALL.m =================================================
+disp(['marshalling file ' name '.bin']);
+fid=fopen([name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' name '.bin file for binary writing']);
+end
+
+%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
+
+%Write all data
+WriteData(fid,'enum',0,'data',x,'format','DoubleMat');
+WriteData(fid,'enum',1,'data',y,'format','DoubleMat');
+WriteData(fid,'enum',2,'data',observations,'format','DoubleMat');
+WriteData(fid,'enum',3,'data',x_interp,'format','DoubleMat');
+WriteData(fid,'enum',4,'data',y_interp,'format','DoubleMat');
+options.marshall(fid,5);
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' name '.bin']);
+end
+% =========================================   MARSHALL.m =================================================
+
+%Launch job on remote cluster
+BuildKrigingQueueScript(cluster,name,'',1,0,0); %gather, valgrind, gprof
+tic
+LaunchQueueJob(cluster,name,name,{[name '.bin'] [name '.queue']});
+toc
+choice=input('Is the job successfully completed? (y/n)','s');
+Download(cluster,name,{[name '.outbin']});
+structure=parseresultsfromdisk([name '.outbin'],0);
+delete([name '.outlog']);
+delete([name '.errlog']);
+delete([name '.outbin']);
+delete([name '.bin']);
+if ~ispc,
+	delete([name '.tar.gz']);
+end
+
+%Process results
+B=structure.AutodiffForward;
+B=reshape(B,size(x_interp,2),size(x_interp,1))';
+E=structure.AutodiffIsautodiff;
+E=reshape(E,size(x_interp,2),size(x_interp,1))';
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/varmap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/varmap.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/gslib/varmap.m	(revision 13101)
@@ -0,0 +1,55 @@
+function output = varmap(x,y,data,varargin);
+%VARMAP - use gslib for Kriging
+%
+%   Usage:
+%      output = varmap(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nxlag = getfieldvalue(options,'nxlag', 20);
+nylag = getfieldvalue(options,'nylag', 20);
+dxlag = getfieldvalue(options,'dxlag', 1000);
+dylag = getfieldvalue(options,'dylag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('varmap.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','0    '                      ,'\1=regular grid, 0=scattered values');
+fprintf(fid,'%-30s %s\n','50 50 1'                    ,'\if =1: nx, ny, nz');
+fprintf(fid,'%-30s %s\n','1.0 1.0 1.0'                ,'\       xsiz, ysiz, zsiz if igrid=1');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\if =0: columns for x, y and z coordinates');
+fprintf(fid,'%-30s %s\n','varmap.out'                 ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str([nxlag nylag 0],'%i '),'\nxlag, nylag, nzlag');
+fprintf(fid,'%-30s %s\n',num2str([dxlag dylag 1],'%g %g %i'),'\dxlag, dylag, dzlag');
+fprintf(fid,'%-30s %s\n','5'                          ,'\minimum number of pairs');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','1'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail, head, variogram type');
+fclose(fid);
+
+%Call varmap
+system([issmdir() '/externalpackages/gslib/install/varmap varmap.par']);
+delete('varmap.par');
+
+%Read output
+fid=fopen('varmap.out','r');
+A = textscan(fid,'%f %f %f %f %f %f','headerlines',8);
+fclose(fid);
+delete('varmap.out')
+output = reshape(A{1},[2*nxlag+1 2*nylag+1]);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/hack/sia.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/hack/sia.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/hack/sia.m	(revision 13101)
@@ -0,0 +1,26 @@
+function [velx,vely,vel]=sia(md)
+%BALVEL - computation of Shallow Ice velocities
+%
+%   This routine uses the model of Hutter to compute the velocities
+%   of a 2d model using the surface slope
+%
+%   Usage:
+%      [velx,vely,vel]=sia(md)
+
+if md.mesh.dimension~=2,
+	error('Only 2d meshes are allowed to compute velocity balances');
+end
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness and B over all elements.
+summer=[1;1;1];
+hel=md.geometry.thickness(md.mesh.elements)*summer/3;
+Bel=md.B(md.mesh.elements)*summer/3;
+
+Ael=Bel.^(-3);
+
+velx=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sx.*Ael/4.*hel.^4;
+vely=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sy.*Ael/4.*hel.^4;
+vel=sqrt(velx.^2+vely.^2);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/hack/thicknessevolution.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/hack/thicknessevolution.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/hack/thicknessevolution.m	(revision 13101)
@@ -0,0 +1,28 @@
+function dhdt=thicknessevolution(md)
+%THICKNESSEVOLUTION - compute the new thickness of a model after ∆t
+%
+%   This routine compute the new thickness of a model after a time step
+%   according to the following formula:
+%   dh/dt=-div(Hu)
+%
+%   Usage:
+%      dhdt=thicknessevolution(md)
+
+if (length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices)
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%load some variables 
+H=md.geometry.thickness;
+vx=md.initialization.vx;
+vy=md.initialization.vy;
+index=md.mesh.elements;
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+%compute dhdt=div(Hu)
+summation=1/3*ones(3,1);
+dhdt=(vx(index)*summation).*sum( H(index).*alpha,2) + (vy(index)*summation).*sum(H(index).*beta,2) ...
+	+ ( H(index)*summation).*sum(vx(index).*alpha,2) + ( H(index)*summation).*sum(vy(index).*beta,2);
+dhdt=-dhdt;
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/hack/tres.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/hack/tres.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/hack/tres.m	(revision 13101)
@@ -0,0 +1,119 @@
+function md=tres(md,string)
+%TRES - transfer results results to corresponding model fields. 
+%
+%    Usage: md=tres(md,string)
+%
+%    Example: md=tres(md,'diagnostic');
+
+%check number of arguments
+
+if strcmpi(string,'diagnostic'),
+	if md.mesh.dimension==2,
+		md.initialization.vx=md.results.DiagnosticSolution.Vx;
+		md.initialization.vy=md.results.DiagnosticSolution.Vy;
+	else 
+		md.initialization.vx=md.results.DiagnosticSolution.Vx;
+		md.initialization.vy=md.results.DiagnosticSolution.Vy;
+		md.initialization.vz=md.results.DiagnosticSolution.Vz;
+	end
+	md.initialization.vel=md.results.DiagnosticSolution.Vel;
+
+	if isfield(md.results.DiagnosticSolution,'Pressure'),
+		md.initialization.pressure=md.results.DiagnosticSolution.Pressure;
+	end
+	if md.rifts.numrifts,
+		if isfield(md.results.DiagnosticSolution,'riftproperties'),
+			md.rifts.riftproperties=md.results.DiagnosticSolution.riftproperties;
+		end
+	end
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			%Will need to be updated... good luck ;)
+			md.(EnumToModelField(control_parameters))=md.results.DiagnosticSolution.(EnumToString(control_parameters));
+		end
+	end
+
+elseif strcmpi(string,'dakota'),
+	md.qmu.results=md.results.dakota;
+
+elseif strcmpi(string,'flaim'),
+	md.flaim.solution=md.results.FlaimSolution.solution;
+	md.flaim.quality =md.results.FlaimSolution.quality;
+
+elseif strcmpi(string,'transient'),
+	results=md.results.TransientSolution;
+	results2.Vel=NaN;
+	count=1;
+	for i=1:length(results),
+		if ~isempty(md.results.TransientSolution(i).Vel),
+			results2(count).Vel=md.results.TransientSolution(i).Vel;
+			results2(count).Surface=md.results.TransientSolution(i).Surface;
+			results2(count).Thickness=md.results.TransientSolution(i).Thickness;
+			results2(count).Bed=md.results.TransientSolution(i).Bed;
+			results2(count).Vx=md.results.TransientSolution(i).Vx;
+			results2(count).Vy=md.results.TransientSolution(i).Vy;
+			results2(count).time=md.results.TransientSolution(i).time;
+			results2(count).step=md.results.TransientSolution(i).step;
+			if ~strcmpi(md.groundingline.migration,'None'),
+				results2(count).ElementOnIceShelf=md.results.TransientSolution(i).ElementOnIceShelf;
+			end
+			count=count+1;
+		end
+	end
+	md.results.TransientSolution=results2;
+	clear results,results2;
+elseif strcmpi(string,'steadystate'),
+	md.initialization.vx=md.results.SteadystateSolution.Vx;
+	md.initialization.vy=md.results.SteadystateSolution.Vy;
+	if isfield(md.results.SteadystateSolution,'Vz'),
+		md.initialization.vz=md.results.SteadystateSolution.Vz;
+	end
+
+	md.initialization.vel=md.results.SteadystateSolution.Vel;
+	md.initialization.pressure=md.results.SteadystateSolution.Pressure;
+	md.initialization.temperature=md.results.SteadystateSolution.Temperature;
+	md.basalforcings.melting_rate=md.results.SteadystateSolution.BasalforcingsMeltingRate;
+
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			md.(EnumToModelField(control_parameters))=md.results.SteadystateSolution.(EnumToString(control_parameters));
+		end
+	end
+
+elseif strcmpi(string,'thermal'),
+	md.initialization.temperature=md.results.ThermalSolution.Temperature;
+	md.basalforcings.melting_rate=md.results.ThermalSolution.BasalMeltingRate;
+elseif strcmpi(string,'hydrology'),
+	md.initialization.watercolumn=md.results.HydrologySolution.Watercolumn;
+
+else 
+	error(['tres error message: analysis ' string ' not supported yet!']);
+end
+end 
+function string=EnumToModelField(enum) % {{{
+	%ENUMTOMODELFIELD - output string of model field associated to enum
+	%
+	%   Usage:
+	%      string=EnumToModelField(enum)
+
+	disp('Warning: EnumToModelField is deprecated, it cannot work with new model definition. This function will be removed in the future');
+
+	switch enum,
+
+		case ThicknessEnum(), string='thickness'; return
+		case FrictionCoefficientEnum(), string='drag_coefficient'; return
+		case MaterialsRheologyBEnum(), string='rheology_B'; return
+		case MaterialsRheologyBbarEnum(), string='rheology_B'; return
+		case BalancethicknessThickeningRateEnum(), string='dhdt'; return
+		case VxEnum(), string='vx'; return
+		case InversionVxObsEnum(), string='vx_obs'; return
+		case VyEnum(), string='vy'; return
+		case InversionVyObsEnum(), string='vy_obs'; return
+		case BasalforcingsMeltingRateEnum(), string='basal_melting_rate'; return
+		case SurfaceforcingsAccumulationRateEnum(), string='surface_accumulation_rate'; return
+		case SurfaceforcingsAblationRateEnum(), string='surface_ablation_rate'; return
+		case SurfaceforcingsMassBalanceEnum(), string='surface_mass_balance'; return
+		otherwise, error(['Enum ' num2str(enum)  ' not found associated to any model field']);
+
+		end
+	end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/hydrology/effectivepressure.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/hydrology/effectivepressure.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/hydrology/effectivepressure.m	(revision 13101)
@@ -0,0 +1,12 @@
+function Neff=effectivepressure(md)
+%EFFECTIVEPRESSURE - compute effective pressure
+%
+%   Usage:
+%      Neff=effectivepressure(md)
+%
+%   Example:
+%      Neff=effectivepressure(md)
+
+Neff=md.materials.rho_ice*md.constants.g*md.geometry.thickness+md.materials.rho_ice*md.constants.g*md.geometry.bed;
+pos=find(Neff<0);
+Neff(pos)=0;
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/contourmassbalance.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/contourmassbalance.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/contourmassbalance.m	(revision 13101)
@@ -0,0 +1,45 @@
+function dhdt=contourmassbalance(md,file)
+%CONTOURMASSBALANCE - compute the mass balance on a contour
+%
+%   Usage:
+%      dhdt=contourmassbalance(md,file)
+
+%some checks
+if nargin~=2,
+	help contourmassbalance
+	error('contourmassbalance error message: bad usage');
+end
+if ((length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices))
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+if ~exist(file),
+	error(['thicknessevolution error message: file ' file ' not found']);
+end
+
+%Get segments enveloping contour
+segments=contourenvelope(md,file);
+%md.diagnostic.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
+
+%get flag list of elements and nodes inside the contour
+nodein=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,file,'node',1);
+elemin=(sum(nodein(md.mesh.elements),2)==size(md.mesh.elements,2));
+
+%conputing Mass flux
+x=md.mesh.x;
+y=md.mesh.y;
+vx=mean(md.initialization.vx(segments(:,1:end-1)),2);
+vy=mean(md.initialization.vy(segments(:,1:end-1)),2);
+H=mean(md.geometry.thickness(segments(:,1:end-1)),2);
+nx=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+ny=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+L=sqrt((x(segments(:,1))-x(segments(:,2))).^2+(y(segments(:,2))-y(segments(:,1))).^2);
+flux = - md.materials.rho_ice*sum(L.*H.*(vx.*nx+vy.*ny)); %outflux is negative!
+disp(['mass outflux on ' file ' = ' num2str(-flux/10^9) ' Gt/yr']);
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+dhdt=flux/(sum(areas(find(elemin)))*md.materials.rho_ice);
+disp(['dhdt on ' file ' (Flux  method) = ' num2str(dhdt) ' m/yr']);
+
+dhdt=thicknessevolution(md);
+in=find(elemin);
+dhdt=sum(dhdt(in).*areas(in))/sum(areas(in));
+disp(['dhdt on ' file ' (divHV method) = ' num2str(dhdt) ' m/yr']);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/divergence.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/divergence.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/divergence.m	(revision 13101)
@@ -0,0 +1,27 @@
+function div=divergence(md,a,b)
+%DIVERGENCE - divergence of [a;b] vector, using model's triangulation.
+%
+%   Usage:
+%      div=divergence(md,a,b)
+
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y; z=md.mesh.z;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+dx=(a(index).*alpha)*summation;
+dy=(b(index).*beta)*summation;
+
+div=dx+dy;
+div=averaging(md,div,1);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/outflow.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/outflow.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/massbalance/outflow.m	(revision 13101)
@@ -0,0 +1,18 @@
+function flag=outflow(md);
+%OUTFLOW - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+Nx=-(md.mesh.y(A)-md.mesh.y(B));
+Ny=  md.mesh.x(A)-md.mesh.x(B);
+Vx=(md.initialization.vx(A)+md.initialization.vx(B))/2;
+Vy=(md.initialization.vy(A)+md.initialization.vy(B))/2;
+
+%dot product
+VdotN=Vx.*Nx+Vy.*Ny;
+
+flag=zeros(md.mesh.numberofvertices,1);
+flag(A(find(VdotN>0)))=1;
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/oasis/carter.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/oasis/carter.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/oasis/carter.m	(revision 13101)
@@ -0,0 +1,28 @@
+function attenuation=carter(temperature)
+%CARTER - attenuation as a function of temperature
+%
+%   TWO WAY - Attenuation (in dB/m) as a function of temperature (K)
+%   From Carter at al. 2007 (Radar-based subglacial lake classification in Antarctica)
+%   Figure 4
+%
+%   Usage:
+%      attenuation=carter(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+Temp=[-50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0]';
+A=[0.0015 0.002 0.003 0.0042 0.0055 0.0083 0.012 0.0175 0.026 0.038 0.055]';
+
+%Now, do a cubic fit between Temp and B: 
+[cfun,gof,output]=fit(Temp,A,'cubicspline');
+%breaks=cfun.p.breaks;
+%coeff=cfun.p.coefs;
+
+%Calculate attenuation
+attenuation=cfun(T);
+
+%Make it a 2 way attenuation
+attenuation=2*attenuation;
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expremovestraightsegments.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expremovestraightsegments.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expremovestraightsegments.m	(revision 13101)
@@ -0,0 +1,31 @@
+function expremovestraightsegments(newfilename,filename,cutoff)
+%EXPREMOVESTRAIGHTSEGMENTS:  remove straight segments connecting contours.
+%
+% Usage: expremovestraightsegments('argus.exp',100); 
+%
+%
+
+a=expread(filename,1);
+newcontours=a(1);
+
+for i=1:length(a),
+	contour=a(i);
+	
+	s=sqrt(contour.x.^2+contour.y.^2);
+	d=diff(s);
+	
+	pos=find(abs(d)>cutoff);
+	pos=[0;pos;length(contour.x)];
+
+	for j=1:length(pos)-1,
+
+		newcontour=contour;
+		newcontour.x=contour.x(pos(j)+1:pos(j+1));
+		newcontour.y=contour.y(pos(j)+1:pos(j+1));
+		newcontour.nods=length(newcontour.x);
+		newcontours(end+1)=newcontour;
+	end
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,newfilename);
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expsplit.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expsplit.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/uci/expsplit.m	(revision 13101)
@@ -0,0 +1,31 @@
+function expsplit(domainoutline)
+%EXPSPLIT - split exp file into sub-contours
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%   This will create as many files there are contours in the domain, each file will be postfix with _i
+%   where i is the contour name. 
+%
+%   Usage:
+%      expsplit(domainoutline)
+%
+%   Example:
+%      expsplit('Domain.exp');
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>1
+	help expsplit
+	error('expsplit error message: bad usage');
+end
+
+[path,root,ext]=fileparts(domainoutline);
+
+%Read file: 
+domains=expread(domainoutline,1);
+
+%split and write contours: 
+for i=1:length(domains),
+	subdomain=domains(i);
+	expwrite(subdomain,[root '_' num2str(i)  ext]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/contrib/uci/pargenerate.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/contrib/uci/pargenerate.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/contrib/uci/pargenerate.m	(revision 13101)
@@ -0,0 +1,45 @@
+function pargenerate(filename,xm,ym,data,varargin)
+%PARGENERATE - generate parameter file for images ala Rignot
+%
+%   Usage: 
+%      pargenerate(filename,data,xm,ym,options);
+%
+%   Supported options:
+%      - title: dataset title
+%      - latitude: standard latitude (degree)
+%      - meridian: meridian (degree)
+%      - format: binary format
+
+%process options
+options=pairoptions(varargin{:});
+Title=getfieldvalue(options,'title','N/A');
+latitude=getfieldvalue(options,'latitude','N/A');
+meridian=getfieldvalue(options,'meridian','N/A');
+format=getfieldvalue(options,'format','single');
+
+%Get data info
+[nlines ncols]=size(data);
+xmin=min(xm);
+ymax=max(ym);
+postx=abs(xm(2)-xm(1));
+posty=abs(ym(2)-ym(1));
+
+%Open header file and get machine type
+fid=fopen(filename,'wt');
+[filename, permission, machineformat, encoding] = fopen(fid);
+
+%write header file
+fprintf(fid,'%s\n','ISSM gridded dataset parameter file');
+fprintf(fid,'%s%s\n','title: ',Title);
+fprintf(fid,'%s  \n','DEM_projection: PS');
+fprintf(fid,'%s%s\n','data_format: ',format);
+fprintf(fid,'%s%s\n','endian:      ',machineformat);
+fprintf(fid,'%s%d\n','width:  ',ncols);
+fprintf(fid,'%s%d\n','nlines: ',nlines);
+fprintf(fid,'%s%g%s\n','PS_secant_lat:    ',latitude,'   decimal degrees');
+fprintf(fid,'%s%g%s\n','PS_meridian_long: ',meridian,'   decimal degrees');
+fprintf(fid,'%s%-15.10g\n','PS_corner_north:  ',ymax);
+fprintf(fid,'%s%-15.10g\n','PS_corner_east:   ',xmin);
+fprintf(fid,'%s%g%s\n','PS_post_north:    ',postx,' m');
+fprintf(fid,'%s%g%s\n','PS_post_east:     ',posty,' m');
+fclose(fid);
Index: sm/branches/trunk-jpl-damage/src/m/enum/AutodiffForwardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/AutodiffForwardEnum.m	(revision 13100)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=AutodiffForwardEnum()
-%AUTODIFFFORWARDENUM - Enum of AutodiffForward
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=AutodiffForwardEnum()
-
-macro=StringToEnum('AutodiffForward');
Index: sm/branches/trunk-jpl-damage/src/m/enum/AutodiffReverseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/AutodiffReverseEnum.m	(revision 13100)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=AutodiffReverseEnum()
-%AUTODIFFREVERSEENUM - Enum of AutodiffReverse
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=AutodiffReverseEnum()
-
-macro=StringToEnum('AutodiffReverse');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py	(revision 13101)
@@ -1,2 +1,4 @@
+from StringToEnum import StringToEnum
+
 """
 
@@ -7,14 +9,4 @@
 """
 
-def AutodiffForwardEnum():
-	"""
-	AUTODIFFFORWARDENUM - Enum of AutodiffForward
-
-	   Usage:
-	      macro=AutodiffForwardEnum()
-	"""
-
-	return StringToEnum('AutodiffForward')
-
 def AutodiffIsautodiffEnum():
 	"""
@@ -25,15 +17,5 @@
 	"""
 
-	return StringToEnum('AutodiffIsautodiff')
-
-def AutodiffReverseEnum():
-	"""
-	AUTODIFFREVERSEENUM - Enum of AutodiffReverse
-
-	   Usage:
-	      macro=AutodiffReverseEnum()
-	"""
-
-	return StringToEnum('AutodiffReverse')
+	return StringToEnum('AutodiffIsautodiff')[0]
 
 def BalancethicknessSpcthicknessEnum():
@@ -45,5 +27,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessSpcthickness')
+	return StringToEnum('BalancethicknessSpcthickness')[0]
 
 def BalancethicknessStabilizationEnum():
@@ -55,5 +37,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessStabilization')
+	return StringToEnum('BalancethicknessStabilization')[0]
 
 def BalancethicknessThickeningRateEnum():
@@ -65,5 +47,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessThickeningRate')
+	return StringToEnum('BalancethicknessThickeningRate')[0]
 
 def BasalforcingsGeothermalfluxEnum():
@@ -75,5 +57,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsGeothermalflux')
+	return StringToEnum('BasalforcingsGeothermalflux')[0]
 
 def BasalforcingsMeltingRateCorrectionEnum():
@@ -85,5 +67,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsMeltingRateCorrection')
+	return StringToEnum('BasalforcingsMeltingRateCorrection')[0]
 
 def BasalforcingsMeltingRateEnum():
@@ -95,5 +77,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsMeltingRate')
+	return StringToEnum('BasalforcingsMeltingRate')[0]
 
 def BathymetryEnum():
@@ -105,5 +87,5 @@
 	"""
 
-	return StringToEnum('Bathymetry')
+	return StringToEnum('Bathymetry')[0]
 
 def BedEnum():
@@ -115,5 +97,5 @@
 	"""
 
-	return StringToEnum('Bed')
+	return StringToEnum('Bed')[0]
 
 def ConstantsGEnum():
@@ -125,5 +107,5 @@
 	"""
 
-	return StringToEnum('ConstantsG')
+	return StringToEnum('ConstantsG')[0]
 
 def ConstantsReferencetemperatureEnum():
@@ -135,5 +117,5 @@
 	"""
 
-	return StringToEnum('ConstantsReferencetemperature')
+	return StringToEnum('ConstantsReferencetemperature')[0]
 
 def ConstantsYtsEnum():
@@ -145,5 +127,5 @@
 	"""
 
-	return StringToEnum('ConstantsYts')
+	return StringToEnum('ConstantsYts')[0]
 
 def DiagnosticAbstolEnum():
@@ -155,5 +137,5 @@
 	"""
 
-	return StringToEnum('DiagnosticAbstol')
+	return StringToEnum('DiagnosticAbstol')[0]
 
 def DiagnosticIcefrontEnum():
@@ -165,5 +147,5 @@
 	"""
 
-	return StringToEnum('DiagnosticIcefront')
+	return StringToEnum('DiagnosticIcefront')[0]
 
 def DiagnosticIsnewtonEnum():
@@ -175,5 +157,5 @@
 	"""
 
-	return StringToEnum('DiagnosticIsnewton')
+	return StringToEnum('DiagnosticIsnewton')[0]
 
 def DiagnosticMaxiterEnum():
@@ -185,5 +167,5 @@
 	"""
 
-	return StringToEnum('DiagnosticMaxiter')
+	return StringToEnum('DiagnosticMaxiter')[0]
 
 def DiagnosticNumRequestedOutputsEnum():
@@ -195,5 +177,5 @@
 	"""
 
-	return StringToEnum('DiagnosticNumRequestedOutputs')
+	return StringToEnum('DiagnosticNumRequestedOutputs')[0]
 
 def DiagnosticPenaltyFactorEnum():
@@ -205,5 +187,5 @@
 	"""
 
-	return StringToEnum('DiagnosticPenaltyFactor')
+	return StringToEnum('DiagnosticPenaltyFactor')[0]
 
 def DiagnosticReferentialEnum():
@@ -215,5 +197,5 @@
 	"""
 
-	return StringToEnum('DiagnosticReferential')
+	return StringToEnum('DiagnosticReferential')[0]
 
 def DiagnosticReltolEnum():
@@ -225,5 +207,5 @@
 	"""
 
-	return StringToEnum('DiagnosticReltol')
+	return StringToEnum('DiagnosticReltol')[0]
 
 def DiagnosticRequestedOutputsEnum():
@@ -235,5 +217,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRequestedOutputs')
+	return StringToEnum('DiagnosticRequestedOutputs')[0]
 
 def DiagnosticRestolEnum():
@@ -245,5 +227,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRestol')
+	return StringToEnum('DiagnosticRestol')[0]
 
 def DiagnosticRiftPenaltyLockEnum():
@@ -255,5 +237,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRiftPenaltyLock')
+	return StringToEnum('DiagnosticRiftPenaltyLock')[0]
 
 def DiagnosticRiftPenaltyThresholdEnum():
@@ -265,5 +247,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRiftPenaltyThreshold')
+	return StringToEnum('DiagnosticRiftPenaltyThreshold')[0]
 
 def DiagnosticShelfDampeningEnum():
@@ -275,5 +257,5 @@
 	"""
 
-	return StringToEnum('DiagnosticShelfDampening')
+	return StringToEnum('DiagnosticShelfDampening')[0]
 
 def DiagnosticSpcvxEnum():
@@ -285,5 +267,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvx')
+	return StringToEnum('DiagnosticSpcvx')[0]
 
 def DiagnosticSpcvyEnum():
@@ -295,5 +277,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvy')
+	return StringToEnum('DiagnosticSpcvy')[0]
 
 def DiagnosticSpcvzEnum():
@@ -305,5 +287,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvz')
+	return StringToEnum('DiagnosticSpcvz')[0]
 
 def DiagnosticStokesreconditioningEnum():
@@ -315,5 +297,5 @@
 	"""
 
-	return StringToEnum('DiagnosticStokesreconditioning')
+	return StringToEnum('DiagnosticStokesreconditioning')[0]
 
 def DiagnosticVertexPairingEnum():
@@ -325,5 +307,5 @@
 	"""
 
-	return StringToEnum('DiagnosticVertexPairing')
+	return StringToEnum('DiagnosticVertexPairing')[0]
 
 def DiagnosticViscosityOvershootEnum():
@@ -335,5 +317,5 @@
 	"""
 
-	return StringToEnum('DiagnosticViscosityOvershoot')
+	return StringToEnum('DiagnosticViscosityOvershoot')[0]
 
 def FlowequationBordermacayealEnum():
@@ -345,5 +327,5 @@
 	"""
 
-	return StringToEnum('FlowequationBordermacayeal')
+	return StringToEnum('FlowequationBordermacayeal')[0]
 
 def FlowequationBorderpattynEnum():
@@ -355,5 +337,5 @@
 	"""
 
-	return StringToEnum('FlowequationBorderpattyn')
+	return StringToEnum('FlowequationBorderpattyn')[0]
 
 def FlowequationBorderstokesEnum():
@@ -365,5 +347,5 @@
 	"""
 
-	return StringToEnum('FlowequationBorderstokes')
+	return StringToEnum('FlowequationBorderstokes')[0]
 
 def FlowequationElementEquationEnum():
@@ -375,5 +357,5 @@
 	"""
 
-	return StringToEnum('FlowequationElementEquation')
+	return StringToEnum('FlowequationElementEquation')[0]
 
 def FlowequationIshutterEnum():
@@ -385,5 +367,15 @@
 	"""
 
-	return StringToEnum('FlowequationIshutter')
+	return StringToEnum('FlowequationIshutter')[0]
+
+def FlowequationIsl1l2Enum():
+	"""
+	FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
+
+	   Usage:
+	      macro=FlowequationIsl1l2Enum()
+	"""
+
+	return StringToEnum('FlowequationIsl1l2')[0]
 
 def FlowequationIsmacayealpattynEnum():
@@ -395,5 +387,5 @@
 	"""
 
-	return StringToEnum('FlowequationIsmacayealpattyn')
+	return StringToEnum('FlowequationIsmacayealpattyn')[0]
 
 def FlowequationIsstokesEnum():
@@ -405,5 +397,5 @@
 	"""
 
-	return StringToEnum('FlowequationIsstokes')
+	return StringToEnum('FlowequationIsstokes')[0]
 
 def FlowequationVertexEquationEnum():
@@ -415,5 +407,5 @@
 	"""
 
-	return StringToEnum('FlowequationVertexEquation')
+	return StringToEnum('FlowequationVertexEquation')[0]
 
 def FrictionCoefficientEnum():
@@ -425,5 +417,5 @@
 	"""
 
-	return StringToEnum('FrictionCoefficient')
+	return StringToEnum('FrictionCoefficient')[0]
 
 def FrictionPEnum():
@@ -435,5 +427,5 @@
 	"""
 
-	return StringToEnum('FrictionP')
+	return StringToEnum('FrictionP')[0]
 
 def FrictionQEnum():
@@ -445,5 +437,5 @@
 	"""
 
-	return StringToEnum('FrictionQ')
+	return StringToEnum('FrictionQ')[0]
 
 def GeometryHydrostaticRatioEnum():
@@ -455,5 +447,5 @@
 	"""
 
-	return StringToEnum('GeometryHydrostaticRatio')
+	return StringToEnum('GeometryHydrostaticRatio')[0]
 
 def HydrologyCREnum():
@@ -465,5 +457,5 @@
 	"""
 
-	return StringToEnum('HydrologyCR')
+	return StringToEnum('HydrologyCR')[0]
 
 def HydrologyKnEnum():
@@ -475,5 +467,5 @@
 	"""
 
-	return StringToEnum('HydrologyKn')
+	return StringToEnum('HydrologyKn')[0]
 
 def HydrologyNEnum():
@@ -485,5 +477,5 @@
 	"""
 
-	return StringToEnum('HydrologyN')
+	return StringToEnum('HydrologyN')[0]
 
 def HydrologyPEnum():
@@ -495,5 +487,5 @@
 	"""
 
-	return StringToEnum('HydrologyP')
+	return StringToEnum('HydrologyP')[0]
 
 def HydrologyQEnum():
@@ -505,5 +497,5 @@
 	"""
 
-	return StringToEnum('HydrologyQ')
+	return StringToEnum('HydrologyQ')[0]
 
 def HydrologySpcwatercolumnEnum():
@@ -515,5 +507,5 @@
 	"""
 
-	return StringToEnum('HydrologySpcwatercolumn')
+	return StringToEnum('HydrologySpcwatercolumn')[0]
 
 def HydrologyStabilizationEnum():
@@ -525,5 +517,5 @@
 	"""
 
-	return StringToEnum('HydrologyStabilization')
+	return StringToEnum('HydrologyStabilization')[0]
 
 def InversionControlParametersEnum():
@@ -535,5 +527,5 @@
 	"""
 
-	return StringToEnum('InversionControlParameters')
+	return StringToEnum('InversionControlParameters')[0]
 
 def InversionCostFunctionEnum():
@@ -545,5 +537,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunction')
+	return StringToEnum('InversionCostFunction')[0]
 
 def InversionCostFunctionThresholdEnum():
@@ -555,5 +547,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctionThreshold')
+	return StringToEnum('InversionCostFunctionThreshold')[0]
 
 def InversionCostFunctionsCoefficientsEnum():
@@ -565,5 +557,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctionsCoefficients')
+	return StringToEnum('InversionCostFunctionsCoefficients')[0]
 
 def InversionCostFunctionsEnum():
@@ -575,5 +567,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctions')
+	return StringToEnum('InversionCostFunctions')[0]
 
 def InversionGradientOnlyEnum():
@@ -585,5 +577,5 @@
 	"""
 
-	return StringToEnum('InversionGradientOnly')
+	return StringToEnum('InversionGradientOnly')[0]
 
 def InversionGradientScalingEnum():
@@ -595,5 +587,5 @@
 	"""
 
-	return StringToEnum('InversionGradientScaling')
+	return StringToEnum('InversionGradientScaling')[0]
 
 def InversionIscontrolEnum():
@@ -605,5 +597,5 @@
 	"""
 
-	return StringToEnum('InversionIscontrol')
+	return StringToEnum('InversionIscontrol')[0]
 
 def InversionTaoEnum():
@@ -615,5 +607,5 @@
 	"""
 
-	return StringToEnum('InversionTao')
+	return StringToEnum('InversionTao')[0]
 
 def InversionIncompleteAdjointEnum():
@@ -625,5 +617,5 @@
 	"""
 
-	return StringToEnum('InversionIncompleteAdjoint')
+	return StringToEnum('InversionIncompleteAdjoint')[0]
 
 def InversionMaxParametersEnum():
@@ -635,5 +627,5 @@
 	"""
 
-	return StringToEnum('InversionMaxParameters')
+	return StringToEnum('InversionMaxParameters')[0]
 
 def InversionMaxiterPerStepEnum():
@@ -645,5 +637,5 @@
 	"""
 
-	return StringToEnum('InversionMaxiterPerStep')
+	return StringToEnum('InversionMaxiterPerStep')[0]
 
 def InversionMinParametersEnum():
@@ -655,5 +647,5 @@
 	"""
 
-	return StringToEnum('InversionMinParameters')
+	return StringToEnum('InversionMinParameters')[0]
 
 def InversionNstepsEnum():
@@ -665,5 +657,5 @@
 	"""
 
-	return StringToEnum('InversionNsteps')
+	return StringToEnum('InversionNsteps')[0]
 
 def InversionNumControlParametersEnum():
@@ -675,5 +667,5 @@
 	"""
 
-	return StringToEnum('InversionNumControlParameters')
+	return StringToEnum('InversionNumControlParameters')[0]
 
 def InversionNumCostFunctionsEnum():
@@ -685,5 +677,5 @@
 	"""
 
-	return StringToEnum('InversionNumCostFunctions')
+	return StringToEnum('InversionNumCostFunctions')[0]
 
 def InversionStepThresholdEnum():
@@ -695,5 +687,5 @@
 	"""
 
-	return StringToEnum('InversionStepThreshold')
+	return StringToEnum('InversionStepThreshold')[0]
 
 def InversionThicknessObsEnum():
@@ -705,5 +697,5 @@
 	"""
 
-	return StringToEnum('InversionThicknessObs')
+	return StringToEnum('InversionThicknessObs')[0]
 
 def InversionVelObsEnum():
@@ -715,5 +707,5 @@
 	"""
 
-	return StringToEnum('InversionVelObs')
+	return StringToEnum('InversionVelObs')[0]
 
 def InversionVxObsEnum():
@@ -725,5 +717,5 @@
 	"""
 
-	return StringToEnum('InversionVxObs')
+	return StringToEnum('InversionVxObs')[0]
 
 def InversionVyObsEnum():
@@ -735,5 +727,5 @@
 	"""
 
-	return StringToEnum('InversionVyObs')
+	return StringToEnum('InversionVyObs')[0]
 
 def InversionVzObsEnum():
@@ -745,5 +737,5 @@
 	"""
 
-	return StringToEnum('InversionVzObs')
+	return StringToEnum('InversionVzObs')[0]
 
 def MaskElementonfloatingiceEnum():
@@ -755,5 +747,5 @@
 	"""
 
-	return StringToEnum('MaskElementonfloatingice')
+	return StringToEnum('MaskElementonfloatingice')[0]
 
 def MaskElementongroundediceEnum():
@@ -765,5 +757,5 @@
 	"""
 
-	return StringToEnum('MaskElementongroundedice')
+	return StringToEnum('MaskElementongroundedice')[0]
 
 def MaskElementonwaterEnum():
@@ -775,5 +767,5 @@
 	"""
 
-	return StringToEnum('MaskElementonwater')
+	return StringToEnum('MaskElementonwater')[0]
 
 def MaskVertexonfloatingiceEnum():
@@ -785,5 +777,5 @@
 	"""
 
-	return StringToEnum('MaskVertexonfloatingice')
+	return StringToEnum('MaskVertexonfloatingice')[0]
 
 def MaskVertexongroundediceEnum():
@@ -795,5 +787,5 @@
 	"""
 
-	return StringToEnum('MaskVertexongroundedice')
+	return StringToEnum('MaskVertexongroundedice')[0]
 
 def MaskVertexonwaterEnum():
@@ -805,5 +797,5 @@
 	"""
 
-	return StringToEnum('MaskVertexonwater')
+	return StringToEnum('MaskVertexonwater')[0]
 
 def MaterialsBetaEnum():
@@ -815,5 +807,5 @@
 	"""
 
-	return StringToEnum('MaterialsBeta')
+	return StringToEnum('MaterialsBeta')[0]
 
 def MaterialsHeatcapacityEnum():
@@ -825,5 +817,5 @@
 	"""
 
-	return StringToEnum('MaterialsHeatcapacity')
+	return StringToEnum('MaterialsHeatcapacity')[0]
 
 def MaterialsLatentheatEnum():
@@ -835,5 +827,5 @@
 	"""
 
-	return StringToEnum('MaterialsLatentheat')
+	return StringToEnum('MaterialsLatentheat')[0]
 
 def MaterialsMeltingpointEnum():
@@ -845,5 +837,5 @@
 	"""
 
-	return StringToEnum('MaterialsMeltingpoint')
+	return StringToEnum('MaterialsMeltingpoint')[0]
 
 def MaterialsMixedLayerCapacityEnum():
@@ -855,5 +847,5 @@
 	"""
 
-	return StringToEnum('MaterialsMixedLayerCapacity')
+	return StringToEnum('MaterialsMixedLayerCapacity')[0]
 
 def MaterialsRheologyBEnum():
@@ -865,5 +857,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyB')
+	return StringToEnum('MaterialsRheologyB')[0]
 
 def MaterialsRheologyBbarEnum():
@@ -875,5 +867,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyBbar')
+	return StringToEnum('MaterialsRheologyBbar')[0]
 
 def MaterialsRheologyLawEnum():
@@ -885,5 +877,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyLaw')
+	return StringToEnum('MaterialsRheologyLaw')[0]
 
 def MaterialsRheologyNEnum():
@@ -895,5 +887,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyN')
+	return StringToEnum('MaterialsRheologyN')[0]
 
 def MaterialsRheologyZEnum():
@@ -905,5 +897,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyZ')
+	return StringToEnum('MaterialsRheologyZ')[0]
 
 def MaterialsRheologyZbarEnum():
@@ -915,5 +907,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyZbar')
+	return StringToEnum('MaterialsRheologyZbar')[0]
 
 def MaterialsRhoIceEnum():
@@ -925,5 +917,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoIce')
+	return StringToEnum('MaterialsRhoIce')[0]
 
 def MaterialsRhoWaterEnum():
@@ -935,5 +927,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoWater')
+	return StringToEnum('MaterialsRhoWater')[0]
 
 def MaterialsRhoFreshwaterEnum():
@@ -945,5 +937,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoFreshwater')
+	return StringToEnum('MaterialsRhoFreshwater')[0]
 
 def MaterialsMuWaterEnum():
@@ -955,5 +947,5 @@
 	"""
 
-	return StringToEnum('MaterialsMuWater')
+	return StringToEnum('MaterialsMuWater')[0]
 
 def MaterialsThermalExchangeVelocityEnum():
@@ -965,5 +957,5 @@
 	"""
 
-	return StringToEnum('MaterialsThermalExchangeVelocity')
+	return StringToEnum('MaterialsThermalExchangeVelocity')[0]
 
 def MaterialsThermalconductivityEnum():
@@ -975,5 +967,5 @@
 	"""
 
-	return StringToEnum('MaterialsThermalconductivity')
+	return StringToEnum('MaterialsThermalconductivity')[0]
 
 def MeshAverageVertexConnectivityEnum():
@@ -985,5 +977,5 @@
 	"""
 
-	return StringToEnum('MeshAverageVertexConnectivity')
+	return StringToEnum('MeshAverageVertexConnectivity')[0]
 
 def MeshDimensionEnum():
@@ -995,5 +987,5 @@
 	"""
 
-	return StringToEnum('MeshDimension')
+	return StringToEnum('MeshDimension')[0]
 
 def MeshEdgesEnum():
@@ -1005,5 +997,5 @@
 	"""
 
-	return StringToEnum('MeshEdges')
+	return StringToEnum('MeshEdges')[0]
 
 def MeshElementconnectivityEnum():
@@ -1015,5 +1007,5 @@
 	"""
 
-	return StringToEnum('MeshElementconnectivity')
+	return StringToEnum('MeshElementconnectivity')[0]
 
 def MeshElementonbedEnum():
@@ -1025,5 +1017,5 @@
 	"""
 
-	return StringToEnum('MeshElementonbed')
+	return StringToEnum('MeshElementonbed')[0]
 
 def MeshElementonsurfaceEnum():
@@ -1035,5 +1027,5 @@
 	"""
 
-	return StringToEnum('MeshElementonsurface')
+	return StringToEnum('MeshElementonsurface')[0]
 
 def MeshElements2dEnum():
@@ -1045,5 +1037,5 @@
 	"""
 
-	return StringToEnum('MeshElements2d')
+	return StringToEnum('MeshElements2d')[0]
 
 def MeshElementsEnum():
@@ -1055,5 +1047,5 @@
 	"""
 
-	return StringToEnum('MeshElements')
+	return StringToEnum('MeshElements')[0]
 
 def MeshLowerelementsEnum():
@@ -1065,5 +1057,5 @@
 	"""
 
-	return StringToEnum('MeshLowerelements')
+	return StringToEnum('MeshLowerelements')[0]
 
 def MeshNumberofedgesEnum():
@@ -1075,5 +1067,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofedges')
+	return StringToEnum('MeshNumberofedges')[0]
 
 def MeshNumberofelements2dEnum():
@@ -1085,5 +1077,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofelements2d')
+	return StringToEnum('MeshNumberofelements2d')[0]
 
 def MeshNumberofelementsEnum():
@@ -1095,5 +1087,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofelements')
+	return StringToEnum('MeshNumberofelements')[0]
 
 def MeshNumberoflayersEnum():
@@ -1105,5 +1097,5 @@
 	"""
 
-	return StringToEnum('MeshNumberoflayers')
+	return StringToEnum('MeshNumberoflayers')[0]
 
 def MeshNumberofvertices2dEnum():
@@ -1115,5 +1107,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofvertices2d')
+	return StringToEnum('MeshNumberofvertices2d')[0]
 
 def MeshNumberofverticesEnum():
@@ -1125,5 +1117,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofvertices')
+	return StringToEnum('MeshNumberofvertices')[0]
 
 def MeshUpperelementsEnum():
@@ -1135,5 +1127,5 @@
 	"""
 
-	return StringToEnum('MeshUpperelements')
+	return StringToEnum('MeshUpperelements')[0]
 
 def MeshVertexonbedEnum():
@@ -1145,5 +1137,5 @@
 	"""
 
-	return StringToEnum('MeshVertexonbed')
+	return StringToEnum('MeshVertexonbed')[0]
 
 def MeshVertexonsurfaceEnum():
@@ -1155,5 +1147,5 @@
 	"""
 
-	return StringToEnum('MeshVertexonsurface')
+	return StringToEnum('MeshVertexonsurface')[0]
 
 def MeshXEnum():
@@ -1165,5 +1157,5 @@
 	"""
 
-	return StringToEnum('MeshX')
+	return StringToEnum('MeshX')[0]
 
 def MeshYEnum():
@@ -1175,5 +1167,5 @@
 	"""
 
-	return StringToEnum('MeshY')
+	return StringToEnum('MeshY')[0]
 
 def MeshZEnum():
@@ -1185,5 +1177,5 @@
 	"""
 
-	return StringToEnum('MeshZ')
+	return StringToEnum('MeshZ')[0]
 
 def MiscellaneousNameEnum():
@@ -1195,5 +1187,5 @@
 	"""
 
-	return StringToEnum('MiscellaneousName')
+	return StringToEnum('MiscellaneousName')[0]
 
 def PrognosticHydrostaticAdjustmentEnum():
@@ -1205,5 +1197,5 @@
 	"""
 
-	return StringToEnum('PrognosticHydrostaticAdjustment')
+	return StringToEnum('PrognosticHydrostaticAdjustment')[0]
 
 def PrognosticMinThicknessEnum():
@@ -1215,5 +1207,5 @@
 	"""
 
-	return StringToEnum('PrognosticMinThickness')
+	return StringToEnum('PrognosticMinThickness')[0]
 
 def PrognosticPenaltyFactorEnum():
@@ -1225,5 +1217,5 @@
 	"""
 
-	return StringToEnum('PrognosticPenaltyFactor')
+	return StringToEnum('PrognosticPenaltyFactor')[0]
 
 def PrognosticSpcthicknessEnum():
@@ -1235,5 +1227,5 @@
 	"""
 
-	return StringToEnum('PrognosticSpcthickness')
+	return StringToEnum('PrognosticSpcthickness')[0]
 
 def PrognosticStabilizationEnum():
@@ -1245,5 +1237,5 @@
 	"""
 
-	return StringToEnum('PrognosticStabilization')
+	return StringToEnum('PrognosticStabilization')[0]
 
 def PrognosticVertexPairingEnum():
@@ -1255,5 +1247,5 @@
 	"""
 
-	return StringToEnum('PrognosticVertexPairing')
+	return StringToEnum('PrognosticVertexPairing')[0]
 
 def QmuIsdakotaEnum():
@@ -1265,5 +1257,5 @@
 	"""
 
-	return StringToEnum('QmuIsdakota')
+	return StringToEnum('QmuIsdakota')[0]
 
 def QmuMassFluxSegmentsEnum():
@@ -1275,5 +1267,5 @@
 	"""
 
-	return StringToEnum('QmuMassFluxSegments')
+	return StringToEnum('QmuMassFluxSegments')[0]
 
 def QmuNumberofpartitionsEnum():
@@ -1285,5 +1277,5 @@
 	"""
 
-	return StringToEnum('QmuNumberofpartitions')
+	return StringToEnum('QmuNumberofpartitions')[0]
 
 def QmuNumberofresponsesEnum():
@@ -1295,5 +1287,5 @@
 	"""
 
-	return StringToEnum('QmuNumberofresponses')
+	return StringToEnum('QmuNumberofresponses')[0]
 
 def QmuPartitionEnum():
@@ -1305,5 +1297,5 @@
 	"""
 
-	return StringToEnum('QmuPartition')
+	return StringToEnum('QmuPartition')[0]
 
 def QmuResponsedescriptorsEnum():
@@ -1315,5 +1307,5 @@
 	"""
 
-	return StringToEnum('QmuResponsedescriptors')
+	return StringToEnum('QmuResponsedescriptors')[0]
 
 def QmuVariabledescriptorsEnum():
@@ -1325,5 +1317,5 @@
 	"""
 
-	return StringToEnum('QmuVariabledescriptors')
+	return StringToEnum('QmuVariabledescriptors')[0]
 
 def RiftsNumriftsEnum():
@@ -1335,5 +1327,5 @@
 	"""
 
-	return StringToEnum('RiftsNumrifts')
+	return StringToEnum('RiftsNumrifts')[0]
 
 def RiftsRiftstructEnum():
@@ -1345,5 +1337,5 @@
 	"""
 
-	return StringToEnum('RiftsRiftstruct')
+	return StringToEnum('RiftsRiftstruct')[0]
 
 def SettingsIoGatherEnum():
@@ -1355,5 +1347,5 @@
 	"""
 
-	return StringToEnum('SettingsIoGather')
+	return StringToEnum('SettingsIoGather')[0]
 
 def SettingsLowmemEnum():
@@ -1365,5 +1357,5 @@
 	"""
 
-	return StringToEnum('SettingsLowmem')
+	return StringToEnum('SettingsLowmem')[0]
 
 def SettingsOutputFrequencyEnum():
@@ -1375,5 +1367,5 @@
 	"""
 
-	return StringToEnum('SettingsOutputFrequency')
+	return StringToEnum('SettingsOutputFrequency')[0]
 
 def SettingsResultsAsPatchesEnum():
@@ -1385,5 +1377,5 @@
 	"""
 
-	return StringToEnum('SettingsResultsAsPatches')
+	return StringToEnum('SettingsResultsAsPatches')[0]
 
 def SettingsWaitonlockEnum():
@@ -1395,5 +1387,5 @@
 	"""
 
-	return StringToEnum('SettingsWaitonlock')
+	return StringToEnum('SettingsWaitonlock')[0]
 
 def SurfaceforcingsDelta18oEnum():
@@ -1405,5 +1397,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsDelta18o')
+	return StringToEnum('SurfaceforcingsDelta18o')[0]
 
 def SurfaceforcingsDelta18oSurfaceEnum():
@@ -1415,5 +1407,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsDelta18oSurface')
+	return StringToEnum('SurfaceforcingsDelta18oSurface')[0]
 
 def SurfaceforcingsIsdelta18oEnum():
@@ -1425,5 +1417,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsIsdelta18o')
+	return StringToEnum('SurfaceforcingsIsdelta18o')[0]
 
 def SurfaceforcingsPrecipitationsPresentdayEnum():
@@ -1435,5 +1427,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsPrecipitationsPresentday')
+	return StringToEnum('SurfaceforcingsPrecipitationsPresentday')[0]
 
 def SurfaceforcingsTemperaturesPresentdayEnum():
@@ -1445,5 +1437,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsTemperaturesPresentday')
+	return StringToEnum('SurfaceforcingsTemperaturesPresentday')[0]
 
 def SurfaceforcingsTemperaturesLgmEnum():
@@ -1455,5 +1447,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsTemperaturesLgm')
+	return StringToEnum('SurfaceforcingsTemperaturesLgm')[0]
 
 def DebugProfilingEnum():
@@ -1465,5 +1457,5 @@
 	"""
 
-	return StringToEnum('DebugProfiling')
+	return StringToEnum('DebugProfiling')[0]
 
 def ProfilingCurrentMemEnum():
@@ -1475,5 +1467,5 @@
 	"""
 
-	return StringToEnum('ProfilingCurrentMem')
+	return StringToEnum('ProfilingCurrentMem')[0]
 
 def ProfilingCurrentFlopsEnum():
@@ -1485,5 +1477,5 @@
 	"""
 
-	return StringToEnum('ProfilingCurrentFlops')
+	return StringToEnum('ProfilingCurrentFlops')[0]
 
 def ProfilingSolutionTimeEnum():
@@ -1495,5 +1487,5 @@
 	"""
 
-	return StringToEnum('ProfilingSolutionTime')
+	return StringToEnum('ProfilingSolutionTime')[0]
 
 def MaxIterationConvergenceFlagEnum():
@@ -1505,5 +1497,5 @@
 	"""
 
-	return StringToEnum('MaxIterationConvergenceFlag')
+	return StringToEnum('MaxIterationConvergenceFlag')[0]
 
 def SteadystateMaxiterEnum():
@@ -1515,5 +1507,5 @@
 	"""
 
-	return StringToEnum('SteadystateMaxiter')
+	return StringToEnum('SteadystateMaxiter')[0]
 
 def SteadystateNumRequestedOutputsEnum():
@@ -1525,5 +1517,5 @@
 	"""
 
-	return StringToEnum('SteadystateNumRequestedOutputs')
+	return StringToEnum('SteadystateNumRequestedOutputs')[0]
 
 def SteadystateReltolEnum():
@@ -1535,5 +1527,5 @@
 	"""
 
-	return StringToEnum('SteadystateReltol')
+	return StringToEnum('SteadystateReltol')[0]
 
 def SteadystateRequestedOutputsEnum():
@@ -1545,5 +1537,5 @@
 	"""
 
-	return StringToEnum('SteadystateRequestedOutputs')
+	return StringToEnum('SteadystateRequestedOutputs')[0]
 
 def SurfaceEnum():
@@ -1555,5 +1547,5 @@
 	"""
 
-	return StringToEnum('Surface')
+	return StringToEnum('Surface')[0]
 
 def SurfaceforcingsPrecipitationEnum():
@@ -1565,5 +1557,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsPrecipitation')
+	return StringToEnum('SurfaceforcingsPrecipitation')[0]
 
 def SurfaceforcingsMassBalanceEnum():
@@ -1575,5 +1567,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsMassBalance')
+	return StringToEnum('SurfaceforcingsMassBalance')[0]
 
 def SurfaceforcingsIspddEnum():
@@ -1585,5 +1577,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsIspdd')
+	return StringToEnum('SurfaceforcingsIspdd')[0]
 
 def SurfaceforcingsIssmbgradientsEnum():
@@ -1595,5 +1587,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsIssmbgradients')
+	return StringToEnum('SurfaceforcingsIssmbgradients')[0]
 
 def SurfaceforcingsMonthlytemperaturesEnum():
@@ -1605,5 +1597,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsMonthlytemperatures')
+	return StringToEnum('SurfaceforcingsMonthlytemperatures')[0]
 
 def SurfaceforcingsHcEnum():
@@ -1615,5 +1607,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsHc')
+	return StringToEnum('SurfaceforcingsHc')[0]
 
 def SurfaceforcingsSmbPosMaxEnum():
@@ -1625,5 +1617,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsSmbPosMax')
+	return StringToEnum('SurfaceforcingsSmbPosMax')[0]
 
 def SurfaceforcingsSmbPosMinEnum():
@@ -1635,5 +1627,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsSmbPosMin')
+	return StringToEnum('SurfaceforcingsSmbPosMin')[0]
 
 def SurfaceforcingsAPosEnum():
@@ -1645,5 +1637,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsAPos')
+	return StringToEnum('SurfaceforcingsAPos')[0]
 
 def SurfaceforcingsBPosEnum():
@@ -1655,5 +1647,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsBPos')
+	return StringToEnum('SurfaceforcingsBPos')[0]
 
 def SurfaceforcingsANegEnum():
@@ -1665,5 +1657,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsANeg')
+	return StringToEnum('SurfaceforcingsANeg')[0]
 
 def SurfaceforcingsBNegEnum():
@@ -1675,5 +1667,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsBNeg')
+	return StringToEnum('SurfaceforcingsBNeg')[0]
 
 def ThermalMaxiterEnum():
@@ -1685,5 +1677,5 @@
 	"""
 
-	return StringToEnum('ThermalMaxiter')
+	return StringToEnum('ThermalMaxiter')[0]
 
 def ThermalPenaltyFactorEnum():
@@ -1695,5 +1687,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyFactor')
+	return StringToEnum('ThermalPenaltyFactor')[0]
 
 def ThermalPenaltyLockEnum():
@@ -1705,5 +1697,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyLock')
+	return StringToEnum('ThermalPenaltyLock')[0]
 
 def ThermalPenaltyThresholdEnum():
@@ -1715,5 +1707,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyThreshold')
+	return StringToEnum('ThermalPenaltyThreshold')[0]
 
 def ThermalSpctemperatureEnum():
@@ -1725,5 +1717,5 @@
 	"""
 
-	return StringToEnum('ThermalSpctemperature')
+	return StringToEnum('ThermalSpctemperature')[0]
 
 def ThermalStabilizationEnum():
@@ -1735,5 +1727,5 @@
 	"""
 
-	return StringToEnum('ThermalStabilization')
+	return StringToEnum('ThermalStabilization')[0]
 
 def ThermalIsenthalpyEnum():
@@ -1745,5 +1737,5 @@
 	"""
 
-	return StringToEnum('ThermalIsenthalpy')
+	return StringToEnum('ThermalIsenthalpy')[0]
 
 def ThicknessEnum():
@@ -1755,5 +1747,5 @@
 	"""
 
-	return StringToEnum('Thickness')
+	return StringToEnum('Thickness')[0]
 
 def TimesteppingStartTimeEnum():
@@ -1765,5 +1757,5 @@
 	"""
 
-	return StringToEnum('TimesteppingStartTime')
+	return StringToEnum('TimesteppingStartTime')[0]
 
 def TimesteppingFinalTimeEnum():
@@ -1775,5 +1767,5 @@
 	"""
 
-	return StringToEnum('TimesteppingFinalTime')
+	return StringToEnum('TimesteppingFinalTime')[0]
 
 def TimesteppingCflCoefficientEnum():
@@ -1785,5 +1777,5 @@
 	"""
 
-	return StringToEnum('TimesteppingCflCoefficient')
+	return StringToEnum('TimesteppingCflCoefficient')[0]
 
 def TimesteppingTimeAdaptEnum():
@@ -1795,5 +1787,5 @@
 	"""
 
-	return StringToEnum('TimesteppingTimeAdapt')
+	return StringToEnum('TimesteppingTimeAdapt')[0]
 
 def TimesteppingTimeStepEnum():
@@ -1805,5 +1797,5 @@
 	"""
 
-	return StringToEnum('TimesteppingTimeStep')
+	return StringToEnum('TimesteppingTimeStep')[0]
 
 def TransientIsdiagnosticEnum():
@@ -1815,5 +1807,5 @@
 	"""
 
-	return StringToEnum('TransientIsdiagnostic')
+	return StringToEnum('TransientIsdiagnostic')[0]
 
 def TransientIsgroundinglineEnum():
@@ -1825,5 +1817,5 @@
 	"""
 
-	return StringToEnum('TransientIsgroundingline')
+	return StringToEnum('TransientIsgroundingline')[0]
 
 def TransientIsprognosticEnum():
@@ -1835,5 +1827,5 @@
 	"""
 
-	return StringToEnum('TransientIsprognostic')
+	return StringToEnum('TransientIsprognostic')[0]
 
 def TransientIsthermalEnum():
@@ -1845,5 +1837,5 @@
 	"""
 
-	return StringToEnum('TransientIsthermal')
+	return StringToEnum('TransientIsthermal')[0]
 
 def TransientNumRequestedOutputsEnum():
@@ -1855,5 +1847,5 @@
 	"""
 
-	return StringToEnum('TransientNumRequestedOutputs')
+	return StringToEnum('TransientNumRequestedOutputs')[0]
 
 def TransientRequestedOutputsEnum():
@@ -1865,5 +1857,5 @@
 	"""
 
-	return StringToEnum('TransientRequestedOutputs')
+	return StringToEnum('TransientRequestedOutputs')[0]
 
 def SolutionTypeEnum():
@@ -1875,5 +1867,5 @@
 	"""
 
-	return StringToEnum('SolutionType')
+	return StringToEnum('SolutionType')[0]
 
 def AnalysisTypeEnum():
@@ -1885,5 +1877,5 @@
 	"""
 
-	return StringToEnum('AnalysisType')
+	return StringToEnum('AnalysisType')[0]
 
 def ConfigurationTypeEnum():
@@ -1895,5 +1887,5 @@
 	"""
 
-	return StringToEnum('ConfigurationType')
+	return StringToEnum('ConfigurationType')[0]
 
 def AdjointBalancethicknessAnalysisEnum():
@@ -1905,5 +1897,5 @@
 	"""
 
-	return StringToEnum('AdjointBalancethicknessAnalysis')
+	return StringToEnum('AdjointBalancethicknessAnalysis')[0]
 
 def AdjointHorizAnalysisEnum():
@@ -1915,5 +1907,5 @@
 	"""
 
-	return StringToEnum('AdjointHorizAnalysis')
+	return StringToEnum('AdjointHorizAnalysis')[0]
 
 def AdjointSolutionEnum():
@@ -1925,5 +1917,5 @@
 	"""
 
-	return StringToEnum('AdjointSolution')
+	return StringToEnum('AdjointSolution')[0]
 
 def AnalysisCounterEnum():
@@ -1935,5 +1927,5 @@
 	"""
 
-	return StringToEnum('AnalysisCounter')
+	return StringToEnum('AnalysisCounter')[0]
 
 def BalancethicknessAnalysisEnum():
@@ -1945,5 +1937,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessAnalysis')
+	return StringToEnum('BalancethicknessAnalysis')[0]
 
 def BalancethicknessSolutionEnum():
@@ -1955,5 +1947,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessSolution')
+	return StringToEnum('BalancethicknessSolution')[0]
 
 def BedSlopeAnalysisEnum():
@@ -1965,5 +1957,5 @@
 	"""
 
-	return StringToEnum('BedSlopeAnalysis')
+	return StringToEnum('BedSlopeAnalysis')[0]
 
 def BedSlopeSolutionEnum():
@@ -1975,5 +1967,5 @@
 	"""
 
-	return StringToEnum('BedSlopeSolution')
+	return StringToEnum('BedSlopeSolution')[0]
 
 def BedSlopeXAnalysisEnum():
@@ -1985,5 +1977,5 @@
 	"""
 
-	return StringToEnum('BedSlopeXAnalysis')
+	return StringToEnum('BedSlopeXAnalysis')[0]
 
 def BedSlopeYAnalysisEnum():
@@ -1995,5 +1987,5 @@
 	"""
 
-	return StringToEnum('BedSlopeYAnalysis')
+	return StringToEnum('BedSlopeYAnalysis')[0]
 
 def DiagnosticHorizAnalysisEnum():
@@ -2005,5 +1997,5 @@
 	"""
 
-	return StringToEnum('DiagnosticHorizAnalysis')
+	return StringToEnum('DiagnosticHorizAnalysis')[0]
 
 def DiagnosticHutterAnalysisEnum():
@@ -2015,5 +2007,5 @@
 	"""
 
-	return StringToEnum('DiagnosticHutterAnalysis')
+	return StringToEnum('DiagnosticHutterAnalysis')[0]
 
 def DiagnosticSolutionEnum():
@@ -2025,5 +2017,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSolution')
+	return StringToEnum('DiagnosticSolution')[0]
 
 def DiagnosticVertAnalysisEnum():
@@ -2035,5 +2027,5 @@
 	"""
 
-	return StringToEnum('DiagnosticVertAnalysis')
+	return StringToEnum('DiagnosticVertAnalysis')[0]
 
 def EnthalpyAnalysisEnum():
@@ -2045,5 +2037,5 @@
 	"""
 
-	return StringToEnum('EnthalpyAnalysis')
+	return StringToEnum('EnthalpyAnalysis')[0]
 
 def EnthalpySolutionEnum():
@@ -2055,5 +2047,5 @@
 	"""
 
-	return StringToEnum('EnthalpySolution')
+	return StringToEnum('EnthalpySolution')[0]
 
 def FlaimAnalysisEnum():
@@ -2065,5 +2057,5 @@
 	"""
 
-	return StringToEnum('FlaimAnalysis')
+	return StringToEnum('FlaimAnalysis')[0]
 
 def FlaimSolutionEnum():
@@ -2075,5 +2067,5 @@
 	"""
 
-	return StringToEnum('FlaimSolution')
+	return StringToEnum('FlaimSolution')[0]
 
 def HydrologyAnalysisEnum():
@@ -2085,5 +2077,5 @@
 	"""
 
-	return StringToEnum('HydrologyAnalysis')
+	return StringToEnum('HydrologyAnalysis')[0]
 
 def HydrologySolutionEnum():
@@ -2095,5 +2087,5 @@
 	"""
 
-	return StringToEnum('HydrologySolution')
+	return StringToEnum('HydrologySolution')[0]
 
 def MeltingAnalysisEnum():
@@ -2105,5 +2097,5 @@
 	"""
 
-	return StringToEnum('MeltingAnalysis')
+	return StringToEnum('MeltingAnalysis')[0]
 
 def NoneAnalysisEnum():
@@ -2115,5 +2107,5 @@
 	"""
 
-	return StringToEnum('NoneAnalysis')
+	return StringToEnum('NoneAnalysis')[0]
 
 def PrognosticAnalysisEnum():
@@ -2125,5 +2117,5 @@
 	"""
 
-	return StringToEnum('PrognosticAnalysis')
+	return StringToEnum('PrognosticAnalysis')[0]
 
 def PrognosticSolutionEnum():
@@ -2135,5 +2127,5 @@
 	"""
 
-	return StringToEnum('PrognosticSolution')
+	return StringToEnum('PrognosticSolution')[0]
 
 def SteadystateSolutionEnum():
@@ -2145,5 +2137,5 @@
 	"""
 
-	return StringToEnum('SteadystateSolution')
+	return StringToEnum('SteadystateSolution')[0]
 
 def SurfaceSlopeAnalysisEnum():
@@ -2155,5 +2147,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeAnalysis')
+	return StringToEnum('SurfaceSlopeAnalysis')[0]
 
 def SurfaceSlopeSolutionEnum():
@@ -2165,5 +2157,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeSolution')
+	return StringToEnum('SurfaceSlopeSolution')[0]
 
 def SurfaceSlopeXAnalysisEnum():
@@ -2175,5 +2167,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeXAnalysis')
+	return StringToEnum('SurfaceSlopeXAnalysis')[0]
 
 def SurfaceSlopeYAnalysisEnum():
@@ -2185,5 +2177,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeYAnalysis')
+	return StringToEnum('SurfaceSlopeYAnalysis')[0]
 
 def ThermalAnalysisEnum():
@@ -2195,5 +2187,5 @@
 	"""
 
-	return StringToEnum('ThermalAnalysis')
+	return StringToEnum('ThermalAnalysis')[0]
 
 def ThermalSolutionEnum():
@@ -2205,5 +2197,5 @@
 	"""
 
-	return StringToEnum('ThermalSolution')
+	return StringToEnum('ThermalSolution')[0]
 
 def TransientSolutionEnum():
@@ -2215,5 +2207,5 @@
 	"""
 
-	return StringToEnum('TransientSolution')
+	return StringToEnum('TransientSolution')[0]
 
 def ApproximationEnum():
@@ -2225,5 +2217,15 @@
 	"""
 
-	return StringToEnum('Approximation')
+	return StringToEnum('Approximation')[0]
+
+def NoneApproximationEnum():
+	"""
+	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
+
+	   Usage:
+	      macro=NoneApproximationEnum()
+	"""
+
+	return StringToEnum('NoneApproximation')[0]
 
 def HutterApproximationEnum():
@@ -2235,5 +2237,5 @@
 	"""
 
-	return StringToEnum('HutterApproximation')
+	return StringToEnum('HutterApproximation')[0]
 
 def MacAyealApproximationEnum():
@@ -2245,5 +2247,5 @@
 	"""
 
-	return StringToEnum('MacAyealApproximation')
+	return StringToEnum('MacAyealApproximation')[0]
 
 def MacAyealPattynApproximationEnum():
@@ -2255,5 +2257,5 @@
 	"""
 
-	return StringToEnum('MacAyealPattynApproximation')
+	return StringToEnum('MacAyealPattynApproximation')[0]
 
 def MacAyealStokesApproximationEnum():
@@ -2265,15 +2267,15 @@
 	"""
 
-	return StringToEnum('MacAyealStokesApproximation')
-
-def NoneApproximationEnum():
-	"""
-	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
-
-	   Usage:
-	      macro=NoneApproximationEnum()
-	"""
-
-	return StringToEnum('NoneApproximation')
+	return StringToEnum('MacAyealStokesApproximation')[0]
+
+def L1L2ApproximationEnum():
+	"""
+	L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
+
+	   Usage:
+	      macro=L1L2ApproximationEnum()
+	"""
+
+	return StringToEnum('L1L2Approximation')[0]
 
 def PattynApproximationEnum():
@@ -2285,5 +2287,5 @@
 	"""
 
-	return StringToEnum('PattynApproximation')
+	return StringToEnum('PattynApproximation')[0]
 
 def PattynStokesApproximationEnum():
@@ -2295,5 +2297,5 @@
 	"""
 
-	return StringToEnum('PattynStokesApproximation')
+	return StringToEnum('PattynStokesApproximation')[0]
 
 def StokesApproximationEnum():
@@ -2305,5 +2307,5 @@
 	"""
 
-	return StringToEnum('StokesApproximation')
+	return StringToEnum('StokesApproximation')[0]
 
 def ConstraintsEnum():
@@ -2315,5 +2317,5 @@
 	"""
 
-	return StringToEnum('Constraints')
+	return StringToEnum('Constraints')[0]
 
 def LoadsEnum():
@@ -2325,5 +2327,5 @@
 	"""
 
-	return StringToEnum('Loads')
+	return StringToEnum('Loads')[0]
 
 def MaterialsEnum():
@@ -2335,5 +2337,5 @@
 	"""
 
-	return StringToEnum('Materials')
+	return StringToEnum('Materials')[0]
 
 def NodesEnum():
@@ -2345,5 +2347,5 @@
 	"""
 
-	return StringToEnum('Nodes')
+	return StringToEnum('Nodes')[0]
 
 def ParametersEnum():
@@ -2355,5 +2357,5 @@
 	"""
 
-	return StringToEnum('Parameters')
+	return StringToEnum('Parameters')[0]
 
 def VerticesEnum():
@@ -2365,5 +2367,5 @@
 	"""
 
-	return StringToEnum('Vertices')
+	return StringToEnum('Vertices')[0]
 
 def ResultsEnum():
@@ -2375,5 +2377,5 @@
 	"""
 
-	return StringToEnum('Results')
+	return StringToEnum('Results')[0]
 
 def BoolInputEnum():
@@ -2385,5 +2387,5 @@
 	"""
 
-	return StringToEnum('BoolInput')
+	return StringToEnum('BoolInput')[0]
 
 def BoolParamEnum():
@@ -2395,5 +2397,5 @@
 	"""
 
-	return StringToEnum('BoolParam')
+	return StringToEnum('BoolParam')[0]
 
 def ContourEnum():
@@ -2405,5 +2407,5 @@
 	"""
 
-	return StringToEnum('Contour')
+	return StringToEnum('Contour')[0]
 
 def ControlInputEnum():
@@ -2415,5 +2417,5 @@
 	"""
 
-	return StringToEnum('ControlInput')
+	return StringToEnum('ControlInput')[0]
 
 def DatasetInputEnum():
@@ -2425,5 +2427,5 @@
 	"""
 
-	return StringToEnum('DatasetInput')
+	return StringToEnum('DatasetInput')[0]
 
 def DofIndexingEnum():
@@ -2435,5 +2437,5 @@
 	"""
 
-	return StringToEnum('DofIndexing')
+	return StringToEnum('DofIndexing')[0]
 
 def DoubleInputEnum():
@@ -2445,5 +2447,5 @@
 	"""
 
-	return StringToEnum('DoubleInput')
+	return StringToEnum('DoubleInput')[0]
 
 def DoubleMatArrayParamEnum():
@@ -2455,5 +2457,5 @@
 	"""
 
-	return StringToEnum('DoubleMatArrayParam')
+	return StringToEnum('DoubleMatArrayParam')[0]
 
 def DoubleMatParamEnum():
@@ -2465,5 +2467,5 @@
 	"""
 
-	return StringToEnum('DoubleMatParam')
+	return StringToEnum('DoubleMatParam')[0]
 
 def DoubleParamEnum():
@@ -2475,5 +2477,5 @@
 	"""
 
-	return StringToEnum('DoubleParam')
+	return StringToEnum('DoubleParam')[0]
 
 def DoubleVecParamEnum():
@@ -2485,5 +2487,5 @@
 	"""
 
-	return StringToEnum('DoubleVecParam')
+	return StringToEnum('DoubleVecParam')[0]
 
 def ElementEnum():
@@ -2495,5 +2497,5 @@
 	"""
 
-	return StringToEnum('Element')
+	return StringToEnum('Element')[0]
 
 def ElementResultEnum():
@@ -2505,5 +2507,5 @@
 	"""
 
-	return StringToEnum('ElementResult')
+	return StringToEnum('ElementResult')[0]
 
 def ExternalResultEnum():
@@ -2515,5 +2517,5 @@
 	"""
 
-	return StringToEnum('ExternalResult')
+	return StringToEnum('ExternalResult')[0]
 
 def FileParamEnum():
@@ -2525,5 +2527,5 @@
 	"""
 
-	return StringToEnum('FileParam')
+	return StringToEnum('FileParam')[0]
 
 def HookEnum():
@@ -2535,5 +2537,5 @@
 	"""
 
-	return StringToEnum('Hook')
+	return StringToEnum('Hook')[0]
 
 def IcefrontEnum():
@@ -2545,5 +2547,5 @@
 	"""
 
-	return StringToEnum('Icefront')
+	return StringToEnum('Icefront')[0]
 
 def InputEnum():
@@ -2555,5 +2557,5 @@
 	"""
 
-	return StringToEnum('Input')
+	return StringToEnum('Input')[0]
 
 def IntInputEnum():
@@ -2565,5 +2567,5 @@
 	"""
 
-	return StringToEnum('IntInput')
+	return StringToEnum('IntInput')[0]
 
 def IntParamEnum():
@@ -2575,5 +2577,5 @@
 	"""
 
-	return StringToEnum('IntParam')
+	return StringToEnum('IntParam')[0]
 
 def IntVecParamEnum():
@@ -2585,5 +2587,5 @@
 	"""
 
-	return StringToEnum('IntVecParam')
+	return StringToEnum('IntVecParam')[0]
 
 def TransientParamEnum():
@@ -2595,5 +2597,5 @@
 	"""
 
-	return StringToEnum('TransientParam')
+	return StringToEnum('TransientParam')[0]
 
 def MacAyeal2dIceFrontEnum():
@@ -2605,5 +2607,5 @@
 	"""
 
-	return StringToEnum('MacAyeal2dIceFront')
+	return StringToEnum('MacAyeal2dIceFront')[0]
 
 def MacAyeal3dIceFrontEnum():
@@ -2615,5 +2617,5 @@
 	"""
 
-	return StringToEnum('MacAyeal3dIceFront')
+	return StringToEnum('MacAyeal3dIceFront')[0]
 
 def MaticeEnum():
@@ -2625,5 +2627,5 @@
 	"""
 
-	return StringToEnum('Matice')
+	return StringToEnum('Matice')[0]
 
 def MatparEnum():
@@ -2635,5 +2637,5 @@
 	"""
 
-	return StringToEnum('Matpar')
+	return StringToEnum('Matpar')[0]
 
 def NodeEnum():
@@ -2645,5 +2647,5 @@
 	"""
 
-	return StringToEnum('Node')
+	return StringToEnum('Node')[0]
 
 def NumericalfluxEnum():
@@ -2655,5 +2657,5 @@
 	"""
 
-	return StringToEnum('Numericalflux')
+	return StringToEnum('Numericalflux')[0]
 
 def ParamEnum():
@@ -2665,5 +2667,15 @@
 	"""
 
-	return StringToEnum('Param')
+	return StringToEnum('Param')[0]
+
+def L1L2IceFrontEnum():
+	"""
+	L1L2ICEFRONTENUM - Enum of L1L2IceFront
+
+	   Usage:
+	      macro=L1L2IceFrontEnum()
+	"""
+
+	return StringToEnum('L1L2IceFront')[0]
 
 def PattynIceFrontEnum():
@@ -2675,5 +2687,5 @@
 	"""
 
-	return StringToEnum('PattynIceFront')
+	return StringToEnum('PattynIceFront')[0]
 
 def PengridEnum():
@@ -2685,5 +2697,5 @@
 	"""
 
-	return StringToEnum('Pengrid')
+	return StringToEnum('Pengrid')[0]
 
 def PenpairEnum():
@@ -2695,5 +2707,5 @@
 	"""
 
-	return StringToEnum('Penpair')
+	return StringToEnum('Penpair')[0]
 
 def PentaEnum():
@@ -2705,5 +2717,5 @@
 	"""
 
-	return StringToEnum('Penta')
+	return StringToEnum('Penta')[0]
 
 def PentaP1InputEnum():
@@ -2715,5 +2727,5 @@
 	"""
 
-	return StringToEnum('PentaP1Input')
+	return StringToEnum('PentaP1Input')[0]
 
 def MatrixParamEnum():
@@ -2725,5 +2737,5 @@
 	"""
 
-	return StringToEnum('MatrixParam')
+	return StringToEnum('MatrixParam')[0]
 
 def VectorParamEnum():
@@ -2735,5 +2747,5 @@
 	"""
 
-	return StringToEnum('VectorParam')
+	return StringToEnum('VectorParam')[0]
 
 def RiftfrontEnum():
@@ -2745,5 +2757,5 @@
 	"""
 
-	return StringToEnum('Riftfront')
+	return StringToEnum('Riftfront')[0]
 
 def SegmentEnum():
@@ -2755,5 +2767,5 @@
 	"""
 
-	return StringToEnum('Segment')
+	return StringToEnum('Segment')[0]
 
 def SegmentRiftfrontEnum():
@@ -2765,5 +2777,5 @@
 	"""
 
-	return StringToEnum('SegmentRiftfront')
+	return StringToEnum('SegmentRiftfront')[0]
 
 def SpcDynamicEnum():
@@ -2775,5 +2787,5 @@
 	"""
 
-	return StringToEnum('SpcDynamic')
+	return StringToEnum('SpcDynamic')[0]
 
 def SpcStaticEnum():
@@ -2785,5 +2797,5 @@
 	"""
 
-	return StringToEnum('SpcStatic')
+	return StringToEnum('SpcStatic')[0]
 
 def SpcTransientEnum():
@@ -2795,5 +2807,5 @@
 	"""
 
-	return StringToEnum('SpcTransient')
+	return StringToEnum('SpcTransient')[0]
 
 def StokesIceFrontEnum():
@@ -2805,5 +2817,5 @@
 	"""
 
-	return StringToEnum('StokesIceFront')
+	return StringToEnum('StokesIceFront')[0]
 
 def StringArrayParamEnum():
@@ -2815,5 +2827,5 @@
 	"""
 
-	return StringToEnum('StringArrayParam')
+	return StringToEnum('StringArrayParam')[0]
 
 def StringParamEnum():
@@ -2825,5 +2837,5 @@
 	"""
 
-	return StringToEnum('StringParam')
+	return StringToEnum('StringParam')[0]
 
 def TriaEnum():
@@ -2835,5 +2847,5 @@
 	"""
 
-	return StringToEnum('Tria')
+	return StringToEnum('Tria')[0]
 
 def TriaP1InputEnum():
@@ -2845,5 +2857,5 @@
 	"""
 
-	return StringToEnum('TriaP1Input')
+	return StringToEnum('TriaP1Input')[0]
 
 def VertexEnum():
@@ -2855,5 +2867,5 @@
 	"""
 
-	return StringToEnum('Vertex')
+	return StringToEnum('Vertex')[0]
 
 def AirEnum():
@@ -2865,5 +2877,5 @@
 	"""
 
-	return StringToEnum('Air')
+	return StringToEnum('Air')[0]
 
 def IceEnum():
@@ -2875,5 +2887,5 @@
 	"""
 
-	return StringToEnum('Ice')
+	return StringToEnum('Ice')[0]
 
 def MelangeEnum():
@@ -2885,5 +2897,5 @@
 	"""
 
-	return StringToEnum('Melange')
+	return StringToEnum('Melange')[0]
 
 def WaterEnum():
@@ -2895,5 +2907,5 @@
 	"""
 
-	return StringToEnum('Water')
+	return StringToEnum('Water')[0]
 
 def ClosedEnum():
@@ -2905,5 +2917,5 @@
 	"""
 
-	return StringToEnum('Closed')
+	return StringToEnum('Closed')[0]
 
 def FreeEnum():
@@ -2915,5 +2927,5 @@
 	"""
 
-	return StringToEnum('Free')
+	return StringToEnum('Free')[0]
 
 def OpenEnum():
@@ -2925,5 +2937,5 @@
 	"""
 
-	return StringToEnum('Open')
+	return StringToEnum('Open')[0]
 
 def AdjointpEnum():
@@ -2935,5 +2947,5 @@
 	"""
 
-	return StringToEnum('Adjointp')
+	return StringToEnum('Adjointp')[0]
 
 def AdjointxEnum():
@@ -2945,5 +2957,5 @@
 	"""
 
-	return StringToEnum('Adjointx')
+	return StringToEnum('Adjointx')[0]
 
 def AdjointyEnum():
@@ -2955,5 +2967,5 @@
 	"""
 
-	return StringToEnum('Adjointy')
+	return StringToEnum('Adjointy')[0]
 
 def AdjointzEnum():
@@ -2965,5 +2977,5 @@
 	"""
 
-	return StringToEnum('Adjointz')
+	return StringToEnum('Adjointz')[0]
 
 def BedSlopeXEnum():
@@ -2975,5 +2987,5 @@
 	"""
 
-	return StringToEnum('BedSlopeX')
+	return StringToEnum('BedSlopeX')[0]
 
 def BedSlopeYEnum():
@@ -2985,5 +2997,5 @@
 	"""
 
-	return StringToEnum('BedSlopeY')
+	return StringToEnum('BedSlopeY')[0]
 
 def BoundaryEnum():
@@ -2995,5 +3007,5 @@
 	"""
 
-	return StringToEnum('Boundary')
+	return StringToEnum('Boundary')[0]
 
 def ConstantEnum():
@@ -3005,5 +3017,5 @@
 	"""
 
-	return StringToEnum('Constant')
+	return StringToEnum('Constant')[0]
 
 def ConvergedEnum():
@@ -3015,5 +3027,5 @@
 	"""
 
-	return StringToEnum('Converged')
+	return StringToEnum('Converged')[0]
 
 def ExtToIuEnum():
@@ -3025,5 +3037,5 @@
 	"""
 
-	return StringToEnum('ExtToIu')
+	return StringToEnum('ExtToIu')[0]
 
 def FillEnum():
@@ -3035,5 +3047,5 @@
 	"""
 
-	return StringToEnum('Fill')
+	return StringToEnum('Fill')[0]
 
 def FractionIncrementEnum():
@@ -3045,5 +3057,5 @@
 	"""
 
-	return StringToEnum('FractionIncrement')
+	return StringToEnum('FractionIncrement')[0]
 
 def FrictionEnum():
@@ -3055,5 +3067,5 @@
 	"""
 
-	return StringToEnum('Friction')
+	return StringToEnum('Friction')[0]
 
 def GroundinglineMeltingRateEnum():
@@ -3065,5 +3077,5 @@
 	"""
 
-	return StringToEnum('GroundinglineMeltingRate')
+	return StringToEnum('GroundinglineMeltingRate')[0]
 
 def InternalEnum():
@@ -3075,5 +3087,5 @@
 	"""
 
-	return StringToEnum('Internal')
+	return StringToEnum('Internal')[0]
 
 def IuToExtEnum():
@@ -3085,5 +3097,5 @@
 	"""
 
-	return StringToEnum('IuToExt')
+	return StringToEnum('IuToExt')[0]
 
 def MassFluxEnum():
@@ -3095,5 +3107,5 @@
 	"""
 
-	return StringToEnum('MassFlux')
+	return StringToEnum('MassFlux')[0]
 
 def MaxPenetrationEnum():
@@ -3105,5 +3117,5 @@
 	"""
 
-	return StringToEnum('MaxPenetration')
+	return StringToEnum('MaxPenetration')[0]
 
 def MeltingOffsetEnum():
@@ -3115,5 +3127,5 @@
 	"""
 
-	return StringToEnum('MeltingOffset')
+	return StringToEnum('MeltingOffset')[0]
 
 def MisfitEnum():
@@ -3125,5 +3137,5 @@
 	"""
 
-	return StringToEnum('Misfit')
+	return StringToEnum('Misfit')[0]
 
 def NumberNodeToElementConnectivityEnum():
@@ -3135,5 +3147,5 @@
 	"""
 
-	return StringToEnum('NumberNodeToElementConnectivity')
+	return StringToEnum('NumberNodeToElementConnectivity')[0]
 
 def PressureEnum():
@@ -3145,5 +3157,5 @@
 	"""
 
-	return StringToEnum('Pressure')
+	return StringToEnum('Pressure')[0]
 
 def PressurePicardEnum():
@@ -3155,5 +3167,5 @@
 	"""
 
-	return StringToEnum('PressurePicard')
+	return StringToEnum('PressurePicard')[0]
 
 def QmuPressureEnum():
@@ -3165,5 +3177,5 @@
 	"""
 
-	return StringToEnum('QmuPressure')
+	return StringToEnum('QmuPressure')[0]
 
 def QmuVxEnum():
@@ -3175,5 +3187,5 @@
 	"""
 
-	return StringToEnum('QmuVx')
+	return StringToEnum('QmuVx')[0]
 
 def QmuVyEnum():
@@ -3185,5 +3197,5 @@
 	"""
 
-	return StringToEnum('QmuVy')
+	return StringToEnum('QmuVy')[0]
 
 def QmuVzEnum():
@@ -3195,5 +3207,5 @@
 	"""
 
-	return StringToEnum('QmuVz')
+	return StringToEnum('QmuVz')[0]
 
 def QmuThicknessEnum():
@@ -3205,5 +3217,5 @@
 	"""
 
-	return StringToEnum('QmuThickness')
+	return StringToEnum('QmuThickness')[0]
 
 def QmuBedEnum():
@@ -3215,5 +3227,5 @@
 	"""
 
-	return StringToEnum('QmuBed')
+	return StringToEnum('QmuBed')[0]
 
 def QmuSurfaceEnum():
@@ -3225,5 +3237,5 @@
 	"""
 
-	return StringToEnum('QmuSurface')
+	return StringToEnum('QmuSurface')[0]
 
 def QmuMeltingEnum():
@@ -3235,5 +3247,5 @@
 	"""
 
-	return StringToEnum('QmuMelting')
+	return StringToEnum('QmuMelting')[0]
 
 def ResetPenaltiesEnum():
@@ -3245,5 +3257,5 @@
 	"""
 
-	return StringToEnum('ResetPenalties')
+	return StringToEnum('ResetPenalties')[0]
 
 def SegmentOnIceShelfEnum():
@@ -3255,5 +3267,5 @@
 	"""
 
-	return StringToEnum('SegmentOnIceShelf')
+	return StringToEnum('SegmentOnIceShelf')[0]
 
 def SurfaceAbsVelMisfitEnum():
@@ -3265,5 +3277,5 @@
 	"""
 
-	return StringToEnum('SurfaceAbsVelMisfit')
+	return StringToEnum('SurfaceAbsVelMisfit')[0]
 
 def SurfaceAreaEnum():
@@ -3275,5 +3287,5 @@
 	"""
 
-	return StringToEnum('SurfaceArea')
+	return StringToEnum('SurfaceArea')[0]
 
 def SurfaceAverageVelMisfitEnum():
@@ -3285,5 +3297,5 @@
 	"""
 
-	return StringToEnum('SurfaceAverageVelMisfit')
+	return StringToEnum('SurfaceAverageVelMisfit')[0]
 
 def SurfaceLogVelMisfitEnum():
@@ -3295,5 +3307,5 @@
 	"""
 
-	return StringToEnum('SurfaceLogVelMisfit')
+	return StringToEnum('SurfaceLogVelMisfit')[0]
 
 def SurfaceLogVxVyMisfitEnum():
@@ -3305,5 +3317,5 @@
 	"""
 
-	return StringToEnum('SurfaceLogVxVyMisfit')
+	return StringToEnum('SurfaceLogVxVyMisfit')[0]
 
 def SurfaceRelVelMisfitEnum():
@@ -3315,5 +3327,5 @@
 	"""
 
-	return StringToEnum('SurfaceRelVelMisfit')
+	return StringToEnum('SurfaceRelVelMisfit')[0]
 
 def SurfaceSlopeXEnum():
@@ -3325,5 +3337,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeX')
+	return StringToEnum('SurfaceSlopeX')[0]
 
 def SurfaceSlopeYEnum():
@@ -3335,5 +3347,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeY')
+	return StringToEnum('SurfaceSlopeY')[0]
 
 def TemperatureEnum():
@@ -3345,5 +3357,5 @@
 	"""
 
-	return StringToEnum('Temperature')
+	return StringToEnum('Temperature')[0]
 
 def TemperatureOldEnum():
@@ -3355,5 +3367,5 @@
 	"""
 
-	return StringToEnum('TemperatureOld')
+	return StringToEnum('TemperatureOld')[0]
 
 def TemperaturePicardEnum():
@@ -3365,5 +3377,5 @@
 	"""
 
-	return StringToEnum('TemperaturePicard')
+	return StringToEnum('TemperaturePicard')[0]
 
 def TemperatureSurfaceEnum():
@@ -3375,5 +3387,5 @@
 	"""
 
-	return StringToEnum('TemperatureSurface')
+	return StringToEnum('TemperatureSurface')[0]
 
 def TemperatureBasalEnum():
@@ -3385,5 +3397,5 @@
 	"""
 
-	return StringToEnum('TemperatureBasal')
+	return StringToEnum('TemperatureBasal')[0]
 
 def ThicknessAbsMisfitEnum():
@@ -3395,5 +3407,5 @@
 	"""
 
-	return StringToEnum('ThicknessAbsMisfit')
+	return StringToEnum('ThicknessAbsMisfit')[0]
 
 def TypeEnum():
@@ -3405,5 +3417,5 @@
 	"""
 
-	return StringToEnum('Type')
+	return StringToEnum('Type')[0]
 
 def VelEnum():
@@ -3415,5 +3427,5 @@
 	"""
 
-	return StringToEnum('Vel')
+	return StringToEnum('Vel')[0]
 
 def VelocityEnum():
@@ -3425,5 +3437,5 @@
 	"""
 
-	return StringToEnum('Velocity')
+	return StringToEnum('Velocity')[0]
 
 def VxAverageEnum():
@@ -3435,5 +3447,5 @@
 	"""
 
-	return StringToEnum('VxAverage')
+	return StringToEnum('VxAverage')[0]
 
 def VxEnum():
@@ -3445,5 +3457,5 @@
 	"""
 
-	return StringToEnum('Vx')
+	return StringToEnum('Vx')[0]
 
 def VxPicardEnum():
@@ -3455,5 +3467,5 @@
 	"""
 
-	return StringToEnum('VxPicard')
+	return StringToEnum('VxPicard')[0]
 
 def VyAverageEnum():
@@ -3465,5 +3477,5 @@
 	"""
 
-	return StringToEnum('VyAverage')
+	return StringToEnum('VyAverage')[0]
 
 def VyEnum():
@@ -3475,5 +3487,5 @@
 	"""
 
-	return StringToEnum('Vy')
+	return StringToEnum('Vy')[0]
 
 def VyPicardEnum():
@@ -3485,5 +3497,5 @@
 	"""
 
-	return StringToEnum('VyPicard')
+	return StringToEnum('VyPicard')[0]
 
 def VzEnum():
@@ -3495,5 +3507,5 @@
 	"""
 
-	return StringToEnum('Vz')
+	return StringToEnum('Vz')[0]
 
 def VzMacAyealEnum():
@@ -3505,5 +3517,5 @@
 	"""
 
-	return StringToEnum('VzMacAyeal')
+	return StringToEnum('VzMacAyeal')[0]
 
 def VzPattynEnum():
@@ -3515,5 +3527,5 @@
 	"""
 
-	return StringToEnum('VzPattyn')
+	return StringToEnum('VzPattyn')[0]
 
 def VzPicardEnum():
@@ -3525,5 +3537,5 @@
 	"""
 
-	return StringToEnum('VzPicard')
+	return StringToEnum('VzPicard')[0]
 
 def VzStokesEnum():
@@ -3535,5 +3547,5 @@
 	"""
 
-	return StringToEnum('VzStokes')
+	return StringToEnum('VzStokes')[0]
 
 def VxMeshEnum():
@@ -3545,5 +3557,5 @@
 	"""
 
-	return StringToEnum('VxMesh')
+	return StringToEnum('VxMesh')[0]
 
 def VyMeshEnum():
@@ -3555,5 +3567,5 @@
 	"""
 
-	return StringToEnum('VyMesh')
+	return StringToEnum('VyMesh')[0]
 
 def VzMeshEnum():
@@ -3565,5 +3577,5 @@
 	"""
 
-	return StringToEnum('VzMesh')
+	return StringToEnum('VzMesh')[0]
 
 def EnthalpyEnum():
@@ -3575,5 +3587,5 @@
 	"""
 
-	return StringToEnum('Enthalpy')
+	return StringToEnum('Enthalpy')[0]
 
 def EnthalpyPicardEnum():
@@ -3585,5 +3597,5 @@
 	"""
 
-	return StringToEnum('EnthalpyPicard')
+	return StringToEnum('EnthalpyPicard')[0]
 
 def ThicknessAbsGradientEnum():
@@ -3595,5 +3607,25 @@
 	"""
 
-	return StringToEnum('ThicknessAbsGradient')
+	return StringToEnum('ThicknessAbsGradient')[0]
+
+def ThicknessAlongGradientEnum():
+	"""
+	THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
+
+	   Usage:
+	      macro=ThicknessAlongGradientEnum()
+	"""
+
+	return StringToEnum('ThicknessAlongGradient')[0]
+
+def ThicknessAcrossGradientEnum():
+	"""
+	THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
+
+	   Usage:
+	      macro=ThicknessAcrossGradientEnum()
+	"""
+
+	return StringToEnum('ThicknessAcrossGradient')[0]
 
 def StepResponsesEnum():
@@ -3605,5 +3637,5 @@
 	"""
 
-	return StringToEnum('StepResponses')
+	return StringToEnum('StepResponses')[0]
 
 def IntMatParamEnum():
@@ -3615,5 +3647,5 @@
 	"""
 
-	return StringToEnum('IntMatParam')
+	return StringToEnum('IntMatParam')[0]
 
 def RheologyBbarAbsGradientEnum():
@@ -3625,5 +3657,5 @@
 	"""
 
-	return StringToEnum('RheologyBbarAbsGradient')
+	return StringToEnum('RheologyBbarAbsGradient')[0]
 
 def DragCoefficientAbsGradientEnum():
@@ -3635,5 +3667,5 @@
 	"""
 
-	return StringToEnum('DragCoefficientAbsGradient')
+	return StringToEnum('DragCoefficientAbsGradient')[0]
 
 def TransientInputEnum():
@@ -3645,5 +3677,5 @@
 	"""
 
-	return StringToEnum('TransientInput')
+	return StringToEnum('TransientInput')[0]
 
 def OutputfilenameEnum():
@@ -3655,5 +3687,5 @@
 	"""
 
-	return StringToEnum('Outputfilename')
+	return StringToEnum('Outputfilename')[0]
 
 def WaterfractionEnum():
@@ -3665,5 +3697,5 @@
 	"""
 
-	return StringToEnum('Waterfraction')
+	return StringToEnum('Waterfraction')[0]
 
 def WatercolumnEnum():
@@ -3675,5 +3707,5 @@
 	"""
 
-	return StringToEnum('Watercolumn')
+	return StringToEnum('Watercolumn')[0]
 
 def BasalFrictionEnum():
@@ -3685,5 +3717,5 @@
 	"""
 
-	return StringToEnum('BasalFriction')
+	return StringToEnum('BasalFriction')[0]
 
 def ViscousHeatingEnum():
@@ -3695,5 +3727,5 @@
 	"""
 
-	return StringToEnum('ViscousHeating')
+	return StringToEnum('ViscousHeating')[0]
 
 def QmuTemperatureEnum():
@@ -3705,5 +3737,5 @@
 	"""
 
-	return StringToEnum('QmuTemperature')
+	return StringToEnum('QmuTemperature')[0]
 
 def HydrologyWaterVxEnum():
@@ -3715,5 +3747,5 @@
 	"""
 
-	return StringToEnum('HydrologyWaterVx')
+	return StringToEnum('HydrologyWaterVx')[0]
 
 def HydrologyWaterVyEnum():
@@ -3725,5 +3757,5 @@
 	"""
 
-	return StringToEnum('HydrologyWaterVy')
+	return StringToEnum('HydrologyWaterVy')[0]
 
 def StressTensorEnum():
@@ -3735,5 +3767,5 @@
 	"""
 
-	return StringToEnum('StressTensor')
+	return StringToEnum('StressTensor')[0]
 
 def StressTensorxxEnum():
@@ -3745,5 +3777,5 @@
 	"""
 
-	return StringToEnum('StressTensorxx')
+	return StringToEnum('StressTensorxx')[0]
 
 def StressTensorxyEnum():
@@ -3755,5 +3787,5 @@
 	"""
 
-	return StringToEnum('StressTensorxy')
+	return StringToEnum('StressTensorxy')[0]
 
 def StressTensorxzEnum():
@@ -3765,5 +3797,5 @@
 	"""
 
-	return StringToEnum('StressTensorxz')
+	return StringToEnum('StressTensorxz')[0]
 
 def StressTensoryyEnum():
@@ -3775,5 +3807,5 @@
 	"""
 
-	return StringToEnum('StressTensoryy')
+	return StringToEnum('StressTensoryy')[0]
 
 def StressTensoryzEnum():
@@ -3785,5 +3817,5 @@
 	"""
 
-	return StringToEnum('StressTensoryz')
+	return StringToEnum('StressTensoryz')[0]
 
 def StressTensorzzEnum():
@@ -3795,5 +3827,335 @@
 	"""
 
-	return StringToEnum('StressTensorzz')
+	return StringToEnum('StressTensorzz')[0]
+
+def P0Enum():
+	"""
+	P0ENUM - Enum of P0
+
+	   Usage:
+	      macro=P0Enum()
+	"""
+
+	return StringToEnum('P0')[0]
+
+def P1Enum():
+	"""
+	P1ENUM - Enum of P1
+
+	   Usage:
+	      macro=P1Enum()
+	"""
+
+	return StringToEnum('P1')[0]
+
+def P1DGEnum():
+	"""
+	P1DGENUM - Enum of P1DG
+
+	   Usage:
+	      macro=P1DGEnum()
+	"""
+
+	return StringToEnum('P1DG')[0]
+
+def SaveResultsEnum():
+	"""
+	SAVERESULTSENUM - Enum of SaveResults
+
+	   Usage:
+	      macro=SaveResultsEnum()
+	"""
+
+	return StringToEnum('SaveResults')[0]
+
+def BoolElementResultEnum():
+	"""
+	BOOLELEMENTRESULTENUM - Enum of BoolElementResult
+
+	   Usage:
+	      macro=BoolElementResultEnum()
+	"""
+
+	return StringToEnum('BoolElementResult')[0]
+
+def BoolExternalResultEnum():
+	"""
+	BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
+
+	   Usage:
+	      macro=BoolExternalResultEnum()
+	"""
+
+	return StringToEnum('BoolExternalResult')[0]
+
+def DoubleElementResultEnum():
+	"""
+	DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
+
+	   Usage:
+	      macro=DoubleElementResultEnum()
+	"""
+
+	return StringToEnum('DoubleElementResult')[0]
+
+def DoubleExternalResultEnum():
+	"""
+	DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
+
+	   Usage:
+	      macro=DoubleExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleExternalResult')[0]
+
+def DoubleMatExternalResultEnum():
+	"""
+	DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
+
+	   Usage:
+	      macro=DoubleMatExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleMatExternalResult')[0]
+
+def DoubleVecExternalResultEnum():
+	"""
+	DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
+
+	   Usage:
+	      macro=DoubleVecExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleVecExternalResult')[0]
+
+def IntExternalResultEnum():
+	"""
+	INTEXTERNALRESULTENUM - Enum of IntExternalResult
+
+	   Usage:
+	      macro=IntExternalResultEnum()
+	"""
+
+	return StringToEnum('IntExternalResult')[0]
+
+def JEnum():
+	"""
+	JENUM - Enum of J
+
+	   Usage:
+	      macro=JEnum()
+	"""
+
+	return StringToEnum('J')[0]
+
+def PatchEnum():
+	"""
+	PATCHENUM - Enum of Patch
+
+	   Usage:
+	      macro=PatchEnum()
+	"""
+
+	return StringToEnum('Patch')[0]
+
+def PatchNodesEnum():
+	"""
+	PATCHNODESENUM - Enum of PatchNodes
+
+	   Usage:
+	      macro=PatchNodesEnum()
+	"""
+
+	return StringToEnum('PatchNodes')[0]
+
+def PatchVerticesEnum():
+	"""
+	PATCHVERTICESENUM - Enum of PatchVertices
+
+	   Usage:
+	      macro=PatchVerticesEnum()
+	"""
+
+	return StringToEnum('PatchVertices')[0]
+
+def PentaP1ElementResultEnum():
+	"""
+	PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
+
+	   Usage:
+	      macro=PentaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('PentaP1ElementResult')[0]
+
+def PetscVecExternalResultEnum():
+	"""
+	PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
+
+	   Usage:
+	      macro=PetscVecExternalResultEnum()
+	"""
+
+	return StringToEnum('PetscVecExternalResult')[0]
+
+def StringExternalResultEnum():
+	"""
+	STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
+
+	   Usage:
+	      macro=StringExternalResultEnum()
+	"""
+
+	return StringToEnum('StringExternalResult')[0]
+
+def StepEnum():
+	"""
+	STEPENUM - Enum of Step
+
+	   Usage:
+	      macro=StepEnum()
+	"""
+
+	return StringToEnum('Step')[0]
+
+def TimeEnum():
+	"""
+	TIMEENUM - Enum of Time
+
+	   Usage:
+	      macro=TimeEnum()
+	"""
+
+	return StringToEnum('Time')[0]
+
+def TriaP1ElementResultEnum():
+	"""
+	TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
+
+	   Usage:
+	      macro=TriaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('TriaP1ElementResult')[0]
+
+def WaterColumnOldEnum():
+	"""
+	WATERCOLUMNOLDENUM - Enum of WaterColumnOld
+
+	   Usage:
+	      macro=WaterColumnOldEnum()
+	"""
+
+	return StringToEnum('WaterColumnOld')[0]
+
+def MinVelEnum():
+	"""
+	MINVELENUM - Enum of MinVel
+
+	   Usage:
+	      macro=MinVelEnum()
+	"""
+
+	return StringToEnum('MinVel')[0]
+
+def MaxVelEnum():
+	"""
+	MAXVELENUM - Enum of MaxVel
+
+	   Usage:
+	      macro=MaxVelEnum()
+	"""
+
+	return StringToEnum('MaxVel')[0]
+
+def MinVxEnum():
+	"""
+	MINVXENUM - Enum of MinVx
+
+	   Usage:
+	      macro=MinVxEnum()
+	"""
+
+	return StringToEnum('MinVx')[0]
+
+def MaxVxEnum():
+	"""
+	MAXVXENUM - Enum of MaxVx
+
+	   Usage:
+	      macro=MaxVxEnum()
+	"""
+
+	return StringToEnum('MaxVx')[0]
+
+def MaxAbsVxEnum():
+	"""
+	MAXABSVXENUM - Enum of MaxAbsVx
+
+	   Usage:
+	      macro=MaxAbsVxEnum()
+	"""
+
+	return StringToEnum('MaxAbsVx')[0]
+
+def MinVyEnum():
+	"""
+	MINVYENUM - Enum of MinVy
+
+	   Usage:
+	      macro=MinVyEnum()
+	"""
+
+	return StringToEnum('MinVy')[0]
+
+def MaxVyEnum():
+	"""
+	MAXVYENUM - Enum of MaxVy
+
+	   Usage:
+	      macro=MaxVyEnum()
+	"""
+
+	return StringToEnum('MaxVy')[0]
+
+def MaxAbsVyEnum():
+	"""
+	MAXABSVYENUM - Enum of MaxAbsVy
+
+	   Usage:
+	      macro=MaxAbsVyEnum()
+	"""
+
+	return StringToEnum('MaxAbsVy')[0]
+
+def MinVzEnum():
+	"""
+	MINVZENUM - Enum of MinVz
+
+	   Usage:
+	      macro=MinVzEnum()
+	"""
+
+	return StringToEnum('MinVz')[0]
+
+def MaxVzEnum():
+	"""
+	MAXVZENUM - Enum of MaxVz
+
+	   Usage:
+	      macro=MaxVzEnum()
+	"""
+
+	return StringToEnum('MaxVz')[0]
+
+def MaxAbsVzEnum():
+	"""
+	MAXABSVZENUM - Enum of MaxAbsVz
+
+	   Usage:
+	      macro=MaxAbsVzEnum()
+	"""
+
+	return StringToEnum('MaxAbsVz')[0]
 
 def IceVolumeEnum():
@@ -3805,5 +4167,5 @@
 	"""
 
-	return StringToEnum('IceVolume')
+	return StringToEnum('IceVolume')[0]
 
 def TotalSmbEnum():
@@ -3815,355 +4177,5 @@
 	"""
 
-	return StringToEnum('TotalSmb')
-
-def ThicknessAlongGradientEnum():
-	"""
-	THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
-
-	   Usage:
-	      macro=ThicknessAlongGradientEnum()
-	"""
-
-	return StringToEnum('ThicknessAlongGradient')
-
-def ThicknessAcrossGradientEnum():
-	"""
-	THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
-
-	   Usage:
-	      macro=ThicknessAcrossGradientEnum()
-	"""
-
-	return StringToEnum('ThicknessAcrossGradient')
-
-def P0Enum():
-	"""
-	P0ENUM - Enum of P0
-
-	   Usage:
-	      macro=P0Enum()
-	"""
-
-	return StringToEnum('P0')
-
-def P1Enum():
-	"""
-	P1ENUM - Enum of P1
-
-	   Usage:
-	      macro=P1Enum()
-	"""
-
-	return StringToEnum('P1')
-
-def P1DGEnum():
-	"""
-	P1DGENUM - Enum of P1DG
-
-	   Usage:
-	      macro=P1DGEnum()
-	"""
-
-	return StringToEnum('P1DG')
-
-def SaveResultsEnum():
-	"""
-	SAVERESULTSENUM - Enum of SaveResults
-
-	   Usage:
-	      macro=SaveResultsEnum()
-	"""
-
-	return StringToEnum('SaveResults')
-
-def BoolElementResultEnum():
-	"""
-	BOOLELEMENTRESULTENUM - Enum of BoolElementResult
-
-	   Usage:
-	      macro=BoolElementResultEnum()
-	"""
-
-	return StringToEnum('BoolElementResult')
-
-def BoolExternalResultEnum():
-	"""
-	BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
-
-	   Usage:
-	      macro=BoolExternalResultEnum()
-	"""
-
-	return StringToEnum('BoolExternalResult')
-
-def DoubleElementResultEnum():
-	"""
-	DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
-
-	   Usage:
-	      macro=DoubleElementResultEnum()
-	"""
-
-	return StringToEnum('DoubleElementResult')
-
-def DoubleExternalResultEnum():
-	"""
-	DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
-
-	   Usage:
-	      macro=DoubleExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleExternalResult')
-
-def DoubleMatExternalResultEnum():
-	"""
-	DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
-
-	   Usage:
-	      macro=DoubleMatExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleMatExternalResult')
-
-def DoubleVecExternalResultEnum():
-	"""
-	DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
-
-	   Usage:
-	      macro=DoubleVecExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleVecExternalResult')
-
-def IntExternalResultEnum():
-	"""
-	INTEXTERNALRESULTENUM - Enum of IntExternalResult
-
-	   Usage:
-	      macro=IntExternalResultEnum()
-	"""
-
-	return StringToEnum('IntExternalResult')
-
-def JEnum():
-	"""
-	JENUM - Enum of J
-
-	   Usage:
-	      macro=JEnum()
-	"""
-
-	return StringToEnum('J')
-
-def PatchEnum():
-	"""
-	PATCHENUM - Enum of Patch
-
-	   Usage:
-	      macro=PatchEnum()
-	"""
-
-	return StringToEnum('Patch')
-
-def PatchNodesEnum():
-	"""
-	PATCHNODESENUM - Enum of PatchNodes
-
-	   Usage:
-	      macro=PatchNodesEnum()
-	"""
-
-	return StringToEnum('PatchNodes')
-
-def PatchVerticesEnum():
-	"""
-	PATCHVERTICESENUM - Enum of PatchVertices
-
-	   Usage:
-	      macro=PatchVerticesEnum()
-	"""
-
-	return StringToEnum('PatchVertices')
-
-def PentaP1ElementResultEnum():
-	"""
-	PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
-
-	   Usage:
-	      macro=PentaP1ElementResultEnum()
-	"""
-
-	return StringToEnum('PentaP1ElementResult')
-
-def PetscVecExternalResultEnum():
-	"""
-	PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
-
-	   Usage:
-	      macro=PetscVecExternalResultEnum()
-	"""
-
-	return StringToEnum('PetscVecExternalResult')
-
-def StringExternalResultEnum():
-	"""
-	STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
-
-	   Usage:
-	      macro=StringExternalResultEnum()
-	"""
-
-	return StringToEnum('StringExternalResult')
-
-def StepEnum():
-	"""
-	STEPENUM - Enum of Step
-
-	   Usage:
-	      macro=StepEnum()
-	"""
-
-	return StringToEnum('Step')
-
-def TimeEnum():
-	"""
-	TIMEENUM - Enum of Time
-
-	   Usage:
-	      macro=TimeEnum()
-	"""
-
-	return StringToEnum('Time')
-
-def TriaP1ElementResultEnum():
-	"""
-	TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
-
-	   Usage:
-	      macro=TriaP1ElementResultEnum()
-	"""
-
-	return StringToEnum('TriaP1ElementResult')
-
-def WaterColumnOldEnum():
-	"""
-	WATERCOLUMNOLDENUM - Enum of WaterColumnOld
-
-	   Usage:
-	      macro=WaterColumnOldEnum()
-	"""
-
-	return StringToEnum('WaterColumnOld')
-
-def MinVelEnum():
-	"""
-	MINVELENUM - Enum of MinVel
-
-	   Usage:
-	      macro=MinVelEnum()
-	"""
-
-	return StringToEnum('MinVel')
-
-def MaxVelEnum():
-	"""
-	MAXVELENUM - Enum of MaxVel
-
-	   Usage:
-	      macro=MaxVelEnum()
-	"""
-
-	return StringToEnum('MaxVel')
-
-def MinVxEnum():
-	"""
-	MINVXENUM - Enum of MinVx
-
-	   Usage:
-	      macro=MinVxEnum()
-	"""
-
-	return StringToEnum('MinVx')
-
-def MaxVxEnum():
-	"""
-	MAXVXENUM - Enum of MaxVx
-
-	   Usage:
-	      macro=MaxVxEnum()
-	"""
-
-	return StringToEnum('MaxVx')
-
-def MaxAbsVxEnum():
-	"""
-	MAXABSVXENUM - Enum of MaxAbsVx
-
-	   Usage:
-	      macro=MaxAbsVxEnum()
-	"""
-
-	return StringToEnum('MaxAbsVx')
-
-def MinVyEnum():
-	"""
-	MINVYENUM - Enum of MinVy
-
-	   Usage:
-	      macro=MinVyEnum()
-	"""
-
-	return StringToEnum('MinVy')
-
-def MaxVyEnum():
-	"""
-	MAXVYENUM - Enum of MaxVy
-
-	   Usage:
-	      macro=MaxVyEnum()
-	"""
-
-	return StringToEnum('MaxVy')
-
-def MaxAbsVyEnum():
-	"""
-	MAXABSVYENUM - Enum of MaxAbsVy
-
-	   Usage:
-	      macro=MaxAbsVyEnum()
-	"""
-
-	return StringToEnum('MaxAbsVy')
-
-def MinVzEnum():
-	"""
-	MINVZENUM - Enum of MinVz
-
-	   Usage:
-	      macro=MinVzEnum()
-	"""
-
-	return StringToEnum('MinVz')
-
-def MaxVzEnum():
-	"""
-	MAXVZENUM - Enum of MaxVz
-
-	   Usage:
-	      macro=MaxVzEnum()
-	"""
-
-	return StringToEnum('MaxVz')
-
-def MaxAbsVzEnum():
-	"""
-	MAXABSVZENUM - Enum of MaxAbsVz
-
-	   Usage:
-	      macro=MaxAbsVzEnum()
-	"""
-
-	return StringToEnum('MaxAbsVz')
+	return StringToEnum('TotalSmb')[0]
 
 def RelativeEnum():
@@ -4175,5 +4187,5 @@
 	"""
 
-	return StringToEnum('Relative')
+	return StringToEnum('Relative')[0]
 
 def AbsoluteEnum():
@@ -4185,5 +4197,5 @@
 	"""
 
-	return StringToEnum('Absolute')
+	return StringToEnum('Absolute')[0]
 
 def IncrementalEnum():
@@ -4195,5 +4207,5 @@
 	"""
 
-	return StringToEnum('Incremental')
+	return StringToEnum('Incremental')[0]
 
 def AgressiveMigrationEnum():
@@ -4205,5 +4217,5 @@
 	"""
 
-	return StringToEnum('AgressiveMigration')
+	return StringToEnum('AgressiveMigration')[0]
 
 def NoneEnum():
@@ -4215,5 +4227,5 @@
 	"""
 
-	return StringToEnum('None')
+	return StringToEnum('None')[0]
 
 def SoftMigrationEnum():
@@ -4225,5 +4237,5 @@
 	"""
 
-	return StringToEnum('SoftMigration')
+	return StringToEnum('SoftMigration')[0]
 
 def StokesSolverEnum():
@@ -4235,5 +4247,5 @@
 	"""
 
-	return StringToEnum('StokesSolver')
+	return StringToEnum('StokesSolver')[0]
 
 def AdjointEnum():
@@ -4245,5 +4257,5 @@
 	"""
 
-	return StringToEnum('Adjoint')
+	return StringToEnum('Adjoint')[0]
 
 def ColinearEnum():
@@ -4255,5 +4267,5 @@
 	"""
 
-	return StringToEnum('Colinear')
+	return StringToEnum('Colinear')[0]
 
 def ControlSteadyEnum():
@@ -4265,5 +4277,5 @@
 	"""
 
-	return StringToEnum('ControlSteady')
+	return StringToEnum('ControlSteady')[0]
 
 def FsetEnum():
@@ -4275,5 +4287,5 @@
 	"""
 
-	return StringToEnum('Fset')
+	return StringToEnum('Fset')[0]
 
 def Gradient1Enum():
@@ -4285,5 +4297,5 @@
 	"""
 
-	return StringToEnum('Gradient1')
+	return StringToEnum('Gradient1')[0]
 
 def Gradient2Enum():
@@ -4295,5 +4307,5 @@
 	"""
 
-	return StringToEnum('Gradient2')
+	return StringToEnum('Gradient2')[0]
 
 def Gradient3Enum():
@@ -4305,5 +4317,5 @@
 	"""
 
-	return StringToEnum('Gradient3')
+	return StringToEnum('Gradient3')[0]
 
 def GradientEnum():
@@ -4315,5 +4327,5 @@
 	"""
 
-	return StringToEnum('Gradient')
+	return StringToEnum('Gradient')[0]
 
 def GroundinglineMigrationEnum():
@@ -4325,5 +4337,5 @@
 	"""
 
-	return StringToEnum('GroundinglineMigration')
+	return StringToEnum('GroundinglineMigration')[0]
 
 def GsetEnum():
@@ -4335,5 +4347,5 @@
 	"""
 
-	return StringToEnum('Gset')
+	return StringToEnum('Gset')[0]
 
 def IndexEnum():
@@ -4345,5 +4357,5 @@
 	"""
 
-	return StringToEnum('Index')
+	return StringToEnum('Index')[0]
 
 def IndexedEnum():
@@ -4355,5 +4367,5 @@
 	"""
 
-	return StringToEnum('Indexed')
+	return StringToEnum('Indexed')[0]
 
 def IntersectEnum():
@@ -4365,5 +4377,5 @@
 	"""
 
-	return StringToEnum('Intersect')
+	return StringToEnum('Intersect')[0]
 
 def NodalEnum():
@@ -4375,5 +4387,5 @@
 	"""
 
-	return StringToEnum('Nodal')
+	return StringToEnum('Nodal')[0]
 
 def OldGradientEnum():
@@ -4385,5 +4397,5 @@
 	"""
 
-	return StringToEnum('OldGradient')
+	return StringToEnum('OldGradient')[0]
 
 def OutputFilePointerEnum():
@@ -4395,5 +4407,5 @@
 	"""
 
-	return StringToEnum('OutputFilePointer')
+	return StringToEnum('OutputFilePointer')[0]
 
 def PetscOptionsAnalysesEnum():
@@ -4405,5 +4417,5 @@
 	"""
 
-	return StringToEnum('PetscOptionsAnalyses')
+	return StringToEnum('PetscOptionsAnalyses')[0]
 
 def PetscOptionsStringsEnum():
@@ -4415,5 +4427,5 @@
 	"""
 
-	return StringToEnum('PetscOptionsStrings')
+	return StringToEnum('PetscOptionsStrings')[0]
 
 def QmuErrNameEnum():
@@ -4425,5 +4437,5 @@
 	"""
 
-	return StringToEnum('QmuErrName')
+	return StringToEnum('QmuErrName')[0]
 
 def QmuInNameEnum():
@@ -4435,5 +4447,5 @@
 	"""
 
-	return StringToEnum('QmuInName')
+	return StringToEnum('QmuInName')[0]
 
 def QmuOutNameEnum():
@@ -4445,5 +4457,5 @@
 	"""
 
-	return StringToEnum('QmuOutName')
+	return StringToEnum('QmuOutName')[0]
 
 def RegularEnum():
@@ -4455,5 +4467,5 @@
 	"""
 
-	return StringToEnum('Regular')
+	return StringToEnum('Regular')[0]
 
 def ScaledEnum():
@@ -4465,5 +4477,5 @@
 	"""
 
-	return StringToEnum('Scaled')
+	return StringToEnum('Scaled')[0]
 
 def SeparateEnum():
@@ -4475,5 +4487,5 @@
 	"""
 
-	return StringToEnum('Separate')
+	return StringToEnum('Separate')[0]
 
 def SsetEnum():
@@ -4485,5 +4497,5 @@
 	"""
 
-	return StringToEnum('Sset')
+	return StringToEnum('Sset')[0]
 
 def VerboseEnum():
@@ -4495,5 +4507,5 @@
 	"""
 
-	return StringToEnum('Verbose')
+	return StringToEnum('Verbose')[0]
 
 def TriangleInterpEnum():
@@ -4505,5 +4517,5 @@
 	"""
 
-	return StringToEnum('TriangleInterp')
+	return StringToEnum('TriangleInterp')[0]
 
 def BilinearInterpEnum():
@@ -4515,5 +4527,5 @@
 	"""
 
-	return StringToEnum('BilinearInterp')
+	return StringToEnum('BilinearInterp')[0]
 
 def NearestInterpEnum():
@@ -4525,5 +4537,5 @@
 	"""
 
-	return StringToEnum('NearestInterp')
+	return StringToEnum('NearestInterp')[0]
 
 def XYEnum():
@@ -4535,5 +4547,5 @@
 	"""
 
-	return StringToEnum('XY')
+	return StringToEnum('XY')[0]
 
 def XYZPEnum():
@@ -4545,5 +4557,5 @@
 	"""
 
-	return StringToEnum('XYZP')
+	return StringToEnum('XYZP')[0]
 
 def OptionEnum():
@@ -4555,5 +4567,5 @@
 	"""
 
-	return StringToEnum('Option')
+	return StringToEnum('Option')[0]
 
 def OptionCellEnum():
@@ -4565,5 +4577,5 @@
 	"""
 
-	return StringToEnum('OptionCell')
+	return StringToEnum('OptionCell')[0]
 
 def OptionCharEnum():
@@ -4575,5 +4587,5 @@
 	"""
 
-	return StringToEnum('OptionChar')
+	return StringToEnum('OptionChar')[0]
 
 def OptionStructEnum():
@@ -4585,5 +4597,5 @@
 	"""
 
-	return StringToEnum('OptionStruct')
+	return StringToEnum('OptionStruct')[0]
 
 def OptionDoubleEnum():
@@ -4595,5 +4607,5 @@
 	"""
 
-	return StringToEnum('OptionDouble')
+	return StringToEnum('OptionDouble')[0]
 
 def OptionLogicalEnum():
@@ -4605,5 +4617,5 @@
 	"""
 
-	return StringToEnum('OptionLogical')
+	return StringToEnum('OptionLogical')[0]
 
 def PatersonEnum():
@@ -4615,5 +4627,5 @@
 	"""
 
-	return StringToEnum('Paterson')
+	return StringToEnum('Paterson')[0]
 
 def ArrheniusEnum():
@@ -4625,5 +4637,5 @@
 	"""
 
-	return StringToEnum('Arrhenius')
+	return StringToEnum('Arrhenius')[0]
 
 def MaximumNumberOfEnums():
@@ -4635,4 +4647,4 @@
 	"""
 
-	return 462
-
+	return 463
+
Index: /issm/branches/trunk-jpl-damage/src/m/enum/FlowequationIsl1l2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/FlowequationIsl1l2Enum.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/FlowequationIsl1l2Enum.m	(revision 13101)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsl1l2Enum()
+%FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsl1l2Enum()
+
+macro=StringToEnum('FlowequationIsl1l2');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/L1L2ApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/L1L2ApproximationEnum.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/L1L2ApproximationEnum.m	(revision 13101)
@@ -0,0 +1,11 @@
+function macro=L1L2ApproximationEnum()
+%L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=L1L2ApproximationEnum()
+
+macro=StringToEnum('L1L2Approximation');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/L1L2IceFrontEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/L1L2IceFrontEnum.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/L1L2IceFrontEnum.m	(revision 13101)
@@ -0,0 +1,11 @@
+function macro=L1L2IceFrontEnum()
+%L1L2ICEFRONTENUM - Enum of L1L2IceFront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=L1L2IceFrontEnum()
+
+macro=StringToEnum('L1L2IceFront');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m	(revision 13101)
@@ -9,3 +9,3 @@
 %      macro=MaximumNumberOfEnums()
 
-macro=462;
+macro=463;
Index: /issm/branches/trunk-jpl-damage/src/m/exp/clicktoflowline.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/clicktoflowline.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/clicktoflowline.m	(revision 13101)
@@ -0,0 +1,24 @@
+function clicktoflowline(index,x,y,u,v,filename)
+%CLICKTOFLOWLINE - create a flowline ARGUS file
+%
+%   create a flowline contour file (named 'filename') by clicking
+%   on a velocity field once (velocity must be plotted first)
+%
+%   Usage: 
+%      clicktoflowline(index,x,y,u,v,x0,y0,filename)
+%
+%   Example: 
+%      clicktoflowline(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vx_obs,md.inversion.vy_obs,'flowline.exp')
+
+%Get click position
+[x0,y0]=ginput(1);
+
+%Get flowline
+line=flowlines(index,x,y,u,v,x0,y0,200);
+
+%plot
+hold on
+plot(line.x,line.y,'r-');
+
+%Write argus file
+expwrite(line,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/downstreamflowlines.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/downstreamflowlines.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/downstreamflowlines.m	(revision 13101)
@@ -0,0 +1,110 @@
+function flowpath=downstreamflowlines(index,x,y,u,v,x0,y0,varargin)
+%DOWNSTREAMFLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=downstreamflowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=downstreamflowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>9 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==9
+	maxiter=varargin{1};%maximum number of iterations
+	precision=varargin{2}; %division of each segment (higer precision increases number of segments)
+else
+	maxiter=200; %maximum number of iterations
+	precision=1; %division of each segment (higer precision increases number of segments)
+end
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expbox.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expbox.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expbox.m	(revision 13101)
@@ -0,0 +1,41 @@
+function expbox(filename)
+%EXPBOX - Create an ARGUS file using two clicks
+%
+%   Two clicks on a plot are used to generate a rectangular box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a rectangular domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+x1=x(1);
+x2=x(2);
+x3=x2;
+x4=x1;
+
+y1=y(1);
+y2=y1;
+y3=y(2);
+y4=y3;
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expcircle.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expcircle.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expcircle.m	(revision 13101)
@@ -0,0 +1,31 @@
+function expcircle(filename,x0,y0,radius,numberofnodes)
+%EXPCIRCLE - create a circular contour corresponding to given parameters
+%
+%   Creates a closed argus contour centered on x,y of radius size.
+%   The contour is made of numberofnodes
+%
+%   Usage:
+%      expcircle(filename,x0,y0,radius,numberofnodes)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(numberofnodes+1,1);
+y_list=ones(numberofnodes+1,1);
+
+theta=(0:2*pi/numberofnodes:2*pi*(1-1/numberofnodes))';
+theta=[theta;0];
+
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+
+%offset x_list and y_list by x0 and y0:
+x_list=x_list+x0;
+y_list=y_list+y0;
+
+contour.x=x_list;
+contour.y=y_list;
+contour.density=1;
+contour.name='circle';
+
+expwrite(contour,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expcoarsen.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expcoarsen.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expcoarsen.m	(revision 13101)
@@ -0,0 +1,74 @@
+function expcoarsen(newfile,oldfile,resolution);
+%EXPCOARSEN - coarsen an exp contour
+%
+%   This routine read an Argus file and remove points with respect to
+%   the resolution (in meters) given in input. 
+%
+%   Usage:
+%      expcoarsen(newfile,oldfile,resolution)
+%
+%   Example:
+%       expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+
+%Some checks
+if nargin~=3 | nargout
+	error('expcoarsen usage: expcoarsen(newfile,oldfile,resolution)')
+elseif ~exist(oldfile)
+	error(['expcut error message: the file ' oldfile  'does not exist'])
+elseif exist(newfile),
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return;
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile);
+numprofiles=size(A,2);
+
+%Go through the profiles
+count=1;
+while count<=numprofiles,
+
+	%get number of points and initialize j
+	numpoints=length(A(count).x);
+	j=1;
+
+	%stop if we have reached end of profile (always keep the last point)
+	while j<numpoints,
+
+		%See whether we keep this point or not
+		distance=sqrt((A(count).x(j)-A(count).x(j+1))^2+(A(count).y(j)-A(count).y(j+1))^2);
+		if distance<resolution & j<numpoints-1  %do not remove last point
+			A(count).x(j+1)=[];
+			A(count).y(j+1)=[];
+			numpoints=numpoints-1;
+		else
+			division=floor(distance/resolution)+1;
+			if division>=2,
+				x=linspace(A(count).x(j),A(count).x(j+1),division)';
+				y=linspace(A(count).y(j),A(count).y(j+1),division)';
+				A(count).x=[A(count).x(1:j);x(2:end-1); A(count).x(j+1:end)];
+				A(count).y=[A(count).y(1:j);y(2:end-1); A(count).y(j+1:end)];
+
+				%update current point
+				j=j+1+division-2;
+				numpoints=numpoints+division-2;
+			else
+				%update current point
+				j=j+1;
+			end
+		end
+	end
+	if length(A(count).x)<=1,
+		A(count)=[];
+		numprofiles=numprofiles-1;
+	else
+		count=count+1;
+	end
+end
+
+%write output
+expwrite(A,newfile);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expcontract.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expcontract.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expcontract.m	(revision 13101)
@@ -0,0 +1,34 @@
+function normal_node=expcontract(newfile,oldfile,distance)
+%EXPCONTRACT - contract or expand a profile, according to the normal.
+% 
+%   Usage:
+%      expcontract(newfile,oldfile,distance)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contour=expread(oldfile);
+num=numel(contour.x);
+
+normal=zeros(num-1,2);
+normal_node=zeros(num-1,2);
+
+for i=1:num-1,
+	normal(i,:)=[ contour.y(i)-contour.y(i+1) contour.x(i+1)-contour.x(i)];
+	normal(i,:)=normal(i,:)/sqrt(normal(i,1)^2+normal(i,2)^2);
+end
+
+normal_node(2:end,:)=[normal(1:end-1,:)+normal(2:end,:)];
+normal_node(1,:)=normal(1,:)+normal(end,:);
+
+normal_node_norm=sqrt(normal_node(:,1).^2+normal_node(:,2).^2);
+normal_node(:,1)=normal_node(:,1)./normal_node_norm;
+normal_node(:,2)=normal_node(:,2)./normal_node_norm;
+
+contour.x(1:end-1)=contour.x(1:end-1)+distance*normal_node(:,1);
+contour.y(1:end-1)=contour.y(1:end-1)+distance*normal_node(:,2);
+
+contour.x(end)=contour.x(1);
+contour.y(end)=contour.y(1);
+
+expwrite(contour,newfile);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expcreatecontour.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expcreatecontour.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expcreatecontour.m	(revision 13101)
@@ -0,0 +1,36 @@
+function expcreatecontour(filename);
+%EXPCREATECONTOUR - create a contour from a list of points
+%
+%   expcreatecontour: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding closed contour.
+%    
+%   Usage:
+%      expcreatecontour(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get contour
+disp('Click on contour points you desire. Type RETURN to end input of points');
+[x,y]=ginput();
+
+%close contour
+x=[x;x(1)];
+y=[y;y(1);];
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write contour using expwrite
+expwrite(a,filename);
+
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expcreateprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expcreateprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expcreateprofile.m	(revision 13101)
@@ -0,0 +1,31 @@
+function expcreateprofile(filename);
+%EXPCREATEPROFILE - create an Argus file from a list of points
+%
+%   expcreateprofile: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding open profile.
+%    
+%   Usage:
+%      expcreateprofile(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get profile
+disp('Click on profile points you desire. Type RETURN to end input of points');
+[x,y]=ginput();
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write profile using expwrite
+expwrite(a,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expdisp.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expdisp.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expdisp.m	(revision 13101)
@@ -0,0 +1,52 @@
+function expdisp(domainoutline,varargin)
+%EXPDISP - plot the contours of a domain outline file
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%
+%   Usage:
+%      expdisp(domainoutline,varargin)
+%      expdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%
+%   Example:
+%      expdisp('Domain.exp',1,'--r',2,10^3);
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>5
+	help expdisp
+	error('expdisp error message: bad usage');
+end
+
+%parse input
+if nargin<=1,
+	figurenumber=1;
+else
+	figurenumber=varargin{1};
+end
+if nargin<=2
+	linestyle='r-';
+else
+	linestyle=varargin{2};
+end
+if nargin<=3
+	linewidth=1;
+else
+	linewidth=varargin{3};
+end
+if nargin<=4
+	unitmultiplier=1;
+else
+	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
+end
+
+domain=expread(domainoutline);
+
+figure(figurenumber),hold on
+for i=1:length(domain),
+	if (isnumeric(linestyle))
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+	else
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expexcludeoutliers.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expexcludeoutliers.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expexcludeoutliers.m	(revision 13101)
@@ -0,0 +1,19 @@
+function excludeoutliers(newcontourname,contourname,domainname)
+%EXCLUDEOUTLIERS - exclude points of contour that are not within the domain
+%contour. return new contours in a different file.
+%
+%        Usage: excludeoutliers('NewContour.exp','Contour.exp','DomainOutline.exp');
+%
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contour=expread(contourname);
+
+for i=1:length(contour),
+	flags=ContourToNodes(contour(i).x,contour(i).y,domainname,0);
+	contour(i).x=contour(i).x(find(flags));
+	contour(i).y=contour(i).y(find(flags));
+end
+
+expwrite(contour,newcontourname);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expflip.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expflip.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expflip.m	(revision 13101)
@@ -0,0 +1,19 @@
+function expflip(domainname)
+%EXPFLIP: flip orientation of all contours and domains in domainname exp file.
+%
+%Usage: expflip('MassFlux1.exp');a
+%
+%
+
+
+
+
+
+a=expread(domainname,1);
+
+for i=1:length(a),
+	a(i).x=flipud(a(i).x);
+	a(i).y=flipud(a(i).y);
+end
+
+expwrite(a,domainname);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/explink.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/explink.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/explink.m	(revision 13101)
@@ -0,0 +1,28 @@
+function explink(domainoutline,minthreshold,step)
+%EXPLINK - allow to link several segments of domain outline together
+%
+%   Takes a domain outline made of various segments, and links them together in one 
+%   domain outline. Use expview to see end result.
+%
+%   Usage:
+%      explink(domainoutline,minthreshold,step)
+%
+%   See also EXPMASTER, EXPDOC
+
+notdone=1;
+
+while notdone,
+
+	for i=1:1000,
+		status=expconcatenate(domainoutline,minthreshold+(i-1)*step);
+		if status==0,
+			return;
+		end
+		if status==1,
+			break;
+		end
+		if status==-1,
+			continue;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expll2xy.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expll2xy.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expll2xy.m	(revision 13101)
@@ -0,0 +1,37 @@
+function expll2xy(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expll2xy(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expll2xy
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).x domain(i).y]= ll2xy(domain(i).y,domain(i).x,sgn,delta,slat);
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expread.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expread.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expread.m	(revision 13101)
@@ -0,0 +1,81 @@
+function Struct=expread(filename);
+%EXPREAD - read a file exp and build a Structure
+%
+%   This routine reads a file .exp and build a Structure containing the 
+%   fields x and y corresponding to the coordinates, one for the filename of
+%   the exp file, for the density, for the nodes, and a field closed to 
+%   indicate if the domain is closed. 
+%   The first argument is the .exp file to be read and the second one (optional) 
+%   indicate if the last point shall be read (1 to read it, 0 not to).
+%
+%   Usage:
+%      Struct=expread(filename)
+%  
+%   Example:
+%      Struct=expread('domainoutline.exp')
+%      Struct=expread('domainoutline.exp')
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+
+%initialize number of profile
+count=0;
+
+%open file
+fid=fopen(filename,'r');
+
+%loop over the number of profiles
+while (~feof(fid)),
+
+	%update number of profiles
+   count=count+1;
+
+   %Get file name
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Name:',7), break; end
+	if length(A)>7, 
+		Struct(count).name=A(8:end);
+	else
+		Struct(count).name='';
+	end
+
+	%Get Icon
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Icon:',6), break; end
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',4);
+	if ~strncmp(A,'#Points',7), break; end
+
+	%Get number of nods and density
+   A=fscanf(fid,'%f %f',[1 2]);
+   Struct(count).nods=A(1);
+   Struct(count).density=A(2);
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',5);
+	if ~strncmp(A,'#XposYpos',9), break; end
+
+	%Get Coordinates
+	A=fscanf(fid,'%f %f',[2 Struct(count).nods]);
+	Struct(count).x=A(1,:)';
+	Struct(count).y=A(2,:)';
+
+	if(Struct(count).nods~=length(Struct(count).x))error(['Profile ' num2str(count) ' reports incorrect length']); end;
+
+	%Check if closed
+	if (Struct(count).nods > 1) && ...
+	   (Struct(count).x(end) == Struct(count).x(1)) && ...
+	   (Struct(count).y(end) == Struct(count).y(1))
+		Struct(count).closed=true;
+	else
+		Struct(count).closed=false;
+	end
+end
+
+%close file
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expsquare.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expsquare.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expsquare.m	(revision 13101)
@@ -0,0 +1,45 @@
+function expsquare(filename)
+%EXPBOX - Create a ARGUS file using to clicks
+%
+%   Two clicks on a plot are used to generate a square box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a square domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+xmiddle=mean(x);
+ymiddle=mean(y);
+
+x1=x(1); y1=y(1);
+x3=x(2); y3=y(2);
+
+Diag=[x1-xmiddle;y1-ymiddle];
+
+Vector=[xmiddle;ymiddle]+[-Diag(2);Diag(1)];
+x2=Vector(1); y2=Vector(2);
+
+Vector=[xmiddle;ymiddle]-[-Diag(2);Diag(1)];
+x4=Vector(1); y4=Vector(2);
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expswapxy.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expswapxy.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expswapxy.m	(revision 13101)
@@ -0,0 +1,23 @@
+function expswapxy(filename)
+%EXPSWAP - swap x and y fields
+% 
+%   Usage:
+%      expswap(file)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contours=expread(filename,1);
+
+newcontours=contours(1);
+
+for i=1:length(contours), 
+	contour=contours(i);
+	newcontour=contour;
+	newcontour.x=contour.y;
+	newcontour.y=contour.x;
+	newcontours(end+1)=newcontour;
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/exptool.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/exptool.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/exptool.m	(revision 13101)
@@ -0,0 +1,351 @@
+function exptool(newfile,varargin)
+%EXPMASTER - allow to create, modify, add, cut, .. segments of domain outline together
+%
+%   this routine is used to create, modify, cut,... an Argus file (.exp)
+%
+%   exptool(newprofile,'optionname',optionvalue)
+%      creation of an argus file newprofile
+%
+%   Available options:
+%      - include: include list of existing ARGUS files
+%      - color: line color (default='r')
+%      - selectioncolor: line color of selected profiles (default='b')
+%      - linestyle (default='-')
+%      - linewidth (default=0.2)
+%      - marker (default='+')
+%      - markersize (default=7)
+%      - markeredgecolor (default='r')
+%
+%   Usage:
+%      exptool(newfile,varargin)
+%
+%   Example:
+%      exptool('domain.exp','include',{'domain1.exp' 'domain2.exp'},'color','g','marker','+')
+%
+%   See also EXPDOC
+
+%recover options
+options=pairoptions(varargin{:});
+
+%Some checks
+if ~nargin | nargout
+	error('exptool usage: exptool(newfile,varargin)')
+elseif exist(newfile,'file'),
+	%recursive call to exptool if file already exists
+	if ~exist(options,'include'),
+		exptool(newfile,'include',newfile,varargin{:});
+		return;
+	end
+
+	%check modification
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Add default options
+options=addfielddefault(options,'color','r');
+options=addfielddefault(options,'selectioncolor','b');
+options=addfielddefault(options,'LineStyle','-');
+options=addfielddefault(options,'LineWidth',0.2);
+options=addfielddefault(options,'Marker','+');
+options=addfielddefault(options,'MarkerSize',7);
+options=addfielddefault(options,'MarkerEdgeColor','r');
+
+%put all the argus profiles given in input in one structure A
+A=struct([]);
+numprofiles=0;
+numpoints=0;
+closed=[];
+
+%initialize the variables with files provided by 'include' option
+if exist(options,'include'),
+	files=getfieldvalue(options,'include');
+	if ischar(files), files={files}; end
+	for i=1:length(files),
+		filename=files{i};
+		if ~exist(filename,'file'),
+			error(['exptool error message:, ' filename ' does not exist. Exiting...']);
+		else
+			%read file
+			B=expread(filename);
+			%go through all profiles of B
+			for i=1:size(B,2)
+				%plug profile in A
+				if numprofiles
+					A(numprofiles+1)=B(i);
+				else
+					A=B(i);
+				end
+				%update numprofiles and numpoints
+				numpoints=numpoints+length(B(i).x);
+				numprofiles=numprofiles+1;
+				%figure out if the profile is closed or not
+				if (B(i).x(1)==B(i).x(end) & B(i).y(1)==B(i).y(end) & length(B(i).x)>1 )
+					closed(numprofiles)=1;
+				else
+					closed(numprofiles)=0;
+				end
+			end
+		end
+	end
+end
+
+%Get root of newfile
+[path root ext]=fileparts(newfile);
+
+%get current figure
+if ~isempty(get(0,'children')),%if there is already a figure (return the number of opened figures)
+	set(gcf,'Renderer','zbuffer'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+	P=get(gcf,'position');
+	F=getframe(gca);
+	F=F.cdata;
+	%get current axis
+	xlim=get(gca,'Xlim');
+	ylim=get(gca,'Ylim');
+	%recreate x_m and y_m
+	x_m=linspace(xlim(1),xlim(2),size(F,2));
+	y_m=linspace(ylim(2),ylim(1),size(F,1)); %getframe reverse axis...
+	%plot the data in another figure
+	figure; set(gcf,'position',P);
+	imagesc(x_m,y_m,F); set(gca,'Ydir','normal');
+	prevplot=1;
+	prevplot2=1;
+else
+	figure
+	prevplot=0;
+	prevplot2=0;
+end
+
+%plot existing profile if any
+hold on
+
+%Build backup structre for do and redo
+backup=cell(1,3);
+backup{1,1}=A;
+backup{1,2}=numprofiles;
+backup{1,3}=numpoints;
+backup{1,4}=closed;
+
+loop=1;
+counter=1;
+while loop
+
+	%Go through A and rule out the empty profiles
+	list=[];
+	for i=1:size(A,2);
+		if length(A(i).x)==0
+			list(end+1)=i;
+			numprofiles=numprofiles-1;
+		end
+	end
+	A(list)=[];
+	closed(list)=[];
+
+	%Now erase all that have been done and plot the new structure A as it is
+	undoplots(prevplot);
+	if numprofiles
+		prevplot2=1;
+		for i=1:numprofiles
+			if length(A(i).x)==1,
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+			else
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			prevplot2=prevplot2+1;
+		end
+	end
+
+	%display menu
+	title('Main Menu','FontSize',14);
+   UIControl_FontSize_bak = get(0, 'DefaultUIControlFontSize');
+   set(0, 'DefaultUIControlFontSize',10);
+   button=menu('exptool menu',...
+      'add a profile (open)',...                %1
+      'add a contour (closed)',...              %2
+      'remove a profile',...                    %3
+      'modify the position of a point',...      %4
+      'add points inside a profile',...         %5
+      'add points at the end of a profile',...  %6
+      'remove points',...                       %7
+      'remove several points',...               %8
+      'cut a segment',...                       %9
+      'cut a large area',...                    %10
+      'merge profiles',...                      %11
+      'close profile',...                       %12
+		'change orientation',...                  %13
+      'undo',...                                %14
+      'redo',...                                %15
+      'quit');                                  %16
+   set(0, 'DefaultUIControlFontSize', UIControl_FontSize_bak);
+
+	%UNDO??
+	if button==14;
+		if counter==1
+			disp('Already at oldest change');
+		else
+			counter=counter-1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	%REDO??
+	elseif button==15
+		if counter==size(backup,1)
+			disp('Already at newest change');
+		else
+			counter=counter+1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	end
+
+	switch button
+
+		case 1
+
+			[A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 2
+
+			[A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 3
+
+			[A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 4
+
+			[A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 5
+
+			[A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 6
+
+			[A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 7
+
+			[A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 8
+
+			[A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 9
+
+			[A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 10
+
+			[A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 11
+
+			[A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+
+		case 12
+
+			[A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 13
+
+			[A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+			%QUIT
+		case 16
+
+			loop=0;
+
+		otherwise
+			%do nothing
+	end
+
+end
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting...','FontSize',14);
+if isempty(A)
+	disp('Profile empty, no file written')
+else
+	expwrite(A,newfile);
+end
+
+%close window
+close;
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expwrite.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expwrite.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expwrite.m	(revision 13101)
@@ -0,0 +1,41 @@
+function expwrite(a,filename);
+%EXPWRITE - write an Argus file from a structure given in input
+%
+%   This routine write an Argus file form a structure containing the fields:
+%   x and y of the coordinates of the points.
+%   The first argument is the structure containing the points coordinates 
+%   and the second one the file to be write.
+%
+%   Usage:
+%      expwrite(a,filename)
+% 
+%   Example:
+%      expwrite(coordstruct,'domainoutline.exp')
+%
+%   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+
+fid=fopen(filename,'w');
+for n=1:length(a),
+	if(length(a(n).x)~=length(a(n).y)),
+		error('contours x and y coordinates must be of identical size');
+	end
+   
+   if isfield(a,'name'),
+	   if ~isempty(a(n).name),
+		   fprintf(fid,'%s%s\n','## Name:',a(n).name);
+	   else
+		   fprintf(fid,'%s\n','## Name:');
+	   end
+   else
+	   fprintf(fid,'%s\n','## Name:');
+   end
+   
+   fprintf(fid,'%s\n','## Icon:0');
+   fprintf(fid,'%s\n','# Points Count Value');
+   fprintf(fid,'%i %f\n',[length(a(n).x) a(n).density]);
+   fprintf(fid,'%s\n','# X pos Y pos');
+	fprintf(fid,'%10.10f %10.10f\n',[a(n).x a(n).y]');
+	fprintf(fid,'\n','');
+   
+end
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/expxy2ll.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/expxy2ll.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/expxy2ll.m	(revision 13101)
@@ -0,0 +1,37 @@
+function expxy2ll(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expxy2ll(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expxy2ll
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).y domain(i).x]= xy2ll(domain(i).x,domain(i).y,sgn,delta,slat); %watch out to swap lat and long
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/branches/trunk-jpl-damage/src/m/exp/flowlines.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/flowlines.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/flowlines.m	(revision 13101)
@@ -0,0 +1,163 @@
+function flowpath=flowlines(index,x,y,u,v,x0,y0,varargin)
+%FLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=flowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=flowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>8 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==8
+	maxiter=varargin{1};
+else
+	maxiter=200; %maximum number of iterations
+end
+precision=1; %division of each segment (higer precision increases number of segments)
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
+
+%same process but reverse (vel=-vel) to have a vcomplete flow line
+counter=1;
+X=x0; Y=y0;
+done=zeros(N,1);
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(1)=[];
+		flowpath(queue(listnan(i))).y(1)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=-u(tria); vt=-v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going backward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision; flowpath(queue(i)).x];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision; flowpath(queue(i)).y];
+	end
+end
+
+%EXP compatibility
+for i=1:length(queue)
+	flowpath(queue(i)).name=['flowline' num2str(i)];
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addcontour.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addcontour.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addcontour.m	(revision 13101)
@@ -0,0 +1,50 @@
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDCONTOUR - add a closed contour
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				x(end+1)=x(1);
+				y(end+1)=y(1);
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=1;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addendprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addendprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addendprofile.m	(revision 13101)
@@ -0,0 +1,86 @@
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDENDPROFILE - add point at the end of a n existing profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if ~any(~closed)
+		disp('all profiles are closed')
+		return
+	end	   
+	%select a profile first
+	if numprofiles>1
+		%first step, select a profile
+		isclosed=1;
+		title('click on a profile, RETURN to exit','FontSize',14)
+		while isclosed
+			[xi,yi] = ginput(1);
+			if ~isempty(xi)
+				%get the closest point 
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if closed(profsel)
+					disp('selected profile is closed, make another selection')
+				else
+					isclosed=0;
+				end
+
+			else
+				%RETURN -> out
+				return
+			end
+		end
+	else
+		profsel=1;
+	end
+
+	%initialize x and y
+	x=A(profsel).x;
+	y=A(profsel).y;
+
+	%plot the selected profile
+	hold on
+	plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+		'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	loop=1;
+	while loop
+
+		%first step, select a profile
+		title('click to add point to the selected profile, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize')+2,'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(profsel).x=x; 
+				A(profsel).y=y; 
+				A(profsel).name=root; 
+				A(profsel).density=1; 
+				numpoints=numpoints+length(x);
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addinsideprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addinsideprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addinsideprofile.m	(revision 13101)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDINSIDEPROFILE - add apoint inside a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are required, exiting...')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%first step, select a segment
+		title('click on a segment, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		%first click
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least two points in one profile are required, exiting...')
+				return
+			end
+
+			%highlight selected segment
+			plot([A(profsel).x(indsel) A(profsel).x(indsel+1)],[A(profsel).y(indsel) A(profsel).y(indsel+1)],...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%next click
+			title('click on the new point''s location, RETURN to exit','FontSize',14)
+			[xi,yi,but] = ginput(1);
+
+			%second click
+			if ~isempty(xi)
+
+				%add point to A
+				A(profsel).x=[A(profsel).x(1:indsel,1); xi; A(profsel).x(indsel+1:end,1)];
+				A(profsel).y=[A(profsel).y(1:indsel,1); yi; A(profsel).y(indsel+1:end,1)];
+				numpoints=numpoints+1;
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+
+			else
+				%RETURN->exit
+				return
+			end
+		else
+			%RETURN-> exit
+			return
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/addprofile.m	(revision 13101)
@@ -0,0 +1,48 @@
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDPROFILE - add a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=0;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closeprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closeprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closeprofile.m	(revision 13101)
@@ -0,0 +1,68 @@
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CLOSEPROFILE - close one or several profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile to be closed')
+		return
+	end
+		   
+	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks,
+		if numprofiles==0    
+			disp('no profile present, exiting...')
+			return            
+		end  
+		if ~any(~closed),
+			disp('All the profiles are closed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from the selection
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			elseif closed(profsel),
+				%profile already closed, do nothing
+				disp('selected profile aready closed, make another selection'),
+			else
+				%add the profile to the list to be closed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%close the profiles
+			for i=1:length(selection),
+				A(selection(i)).x(end+1)=A(selection(i)).x(1);
+				A(selection(i)).y(end+1)=A(selection(i)).y(1);
+				numpoints=numpoints+1;
+				closed(selection(i))=1;
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestpoint.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestpoint.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestpoint.m	(revision 13101)
@@ -0,0 +1,21 @@
+function [profsel indsel]=closestpoint(A,numprofiles,xi,yi)
+%CLOSESTPOINT - find the closest point of a profile
+%
+%   This routine find the point of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the point
+%
+%   Usage:
+%     [profsel indsel]=closestpoint(A,numprofiles,xi,yi) 
+
+	%loop over the points of each profile, find the closest to (xi,yi)
+	for i=1:numprofiles,
+		distance=(xi-A(i).x).^2+(yi-A(i).y).^2;
+		[newdistance p]=min(distance);
+		if ((i==1) | (newdistance<olddistance)),
+			indsel=p;
+			profsel=i;
+			olddistance=newdistance;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestsegment.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestsegment.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/closestsegment.m	(revision 13101)
@@ -0,0 +1,28 @@
+function [profsel indsel]=closestsegment(A,numprofiles,xi,yi)
+%CLOSESTSEGMENT - find the closest segment of a profile
+%
+%   This routine find the segment of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the first point belonging to this closest segment
+%
+%   Usage:
+%     [profsel indsel]=closestsegment(A,numprofiles,xi,yi) 
+
+	%loop over the middles of each profile, find the closest to (xi,yi)
+	profsel=0;
+	indsel=0;
+	first=1;
+	for i=1:numprofiles,
+		if length(A(i).x)>1
+			middles=[(A(i).x(1:end-1)+A(i).x(2:end))/2 (A(i).y(1:end-1)+A(i).y(2:end))/2];
+			distance=(xi-middles(:,1)).^2+(yi-middles(:,2)).^2;
+			[newdistance p]=min(distance);
+			if (first | (newdistance<olddistance)),
+				first=0;
+				indsel=p;
+				profsel=i;
+				olddistance=newdistance;
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutarea.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutarea.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutarea.m	(revision 13101)
@@ -0,0 +1,156 @@
+function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CUTAREA - cut several point of a profile
+%
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must click 3 times to select the
+%   area to be removed. Twice to select the tips and one to select
+%   the part of the profile to be removed
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile present, exiting...')
+			return
+		end	   
+		if numpoints<3
+			disp('at least two points are needed, exiting...')
+			return
+		end	   
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be cut, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						x=A(selection).x; y=A(selection).y;
+						if p1<p2
+							if p3>p1 & p3<p2
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p2:end-1,1);A(selection).x(1:p1,1)];
+									A(selection).y=[A(selection).y(p2:end-1,1);A(selection).y(1:p1,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									A(selection).x=x(1:p1);
+									A(selection).y=y(1:p1);
+									closed(selection)=0;
+									A(end+1).x=x(p2:end);
+									A(end).y=y(p2:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p2-p1-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								A(selection).x=x(p1:p2);
+								A(selection).y=y(p1:p2);
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						else
+							if p3>p2 & p3<p1
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p1:end-1,1);A(selection).x(1:p2,1)];
+									A(selection).y=[A(selection).y(p1:end-1,1);A(selection).y(1:p2,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									closed(selection)=0;
+									A(selection).x=x(1:p2);
+									A(selection).y=y(1:p2);
+									A(end+1).x=x(p1:end);
+									A(end).y=y(p1:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p1-p2-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								x(1:p2-1)=[];x(p1-p2+2:end)=[];%it should have been x(p2+1:end)
+								y(1:p2-1)=[];y(p1-p2+2:end)=[];
+								A(selection).x=x;
+								A(selection).y=y;
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						end
+
+						%plot new profile
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/cutprofile.m	(revision 13101)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CUTPROFILE - cut a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are needed')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%select a segment
+		title('click the segment to cut, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least 2 points are required');
+				return,
+			end
+
+			if ((closed(profsel) & length(A(profsel).x)<3) | (~closed(profsel) & length(A(profsel).x)<2))
+				disp('at least 2 points are required, make another selection');
+			else
+				%cut A
+				if closed(profsel)
+					%open the contour
+					A(profsel).x=[A(profsel).x(indsel+1:end-1,1);A(profsel).x(1:indsel,1)];
+					A(profsel).y=[A(profsel).y(indsel+1:end-1,1);A(profsel).y(1:indsel,1)];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				else
+					%cut the contour in 2 profiles
+					A(end+1).x=A(profsel).x(indsel+1:end,1);
+					A(end).y=A(profsel).y(indsel+1:end,1);
+					A(end).name=root; 
+					A(end).density=1; 
+					A(profsel).x=A(profsel).x(1:indsel,1);
+					A(profsel).y=A(profsel).y(1:indsel,1);
+					numprofiles=numprofiles+1;
+					closed(end+1)=0;
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			end
+		else
+			%RETURN->exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/mergeprofiles.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/mergeprofiles.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/mergeprofiles.m	(revision 13101)
@@ -0,0 +1,152 @@
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MERGEPROFILES - merge profiles
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must select the two tips that
+%   he/she wants to merge
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+hold on
+loop=1;
+
+%Take all the tips coordinates of open profiles
+counter=1; tips=[];
+for i=1:numprofiles
+	if ~closed(i),
+		%x and y coord, profile number, 1 if beginning, 2 and if end
+		if length(A(i).x)==1,
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			counter=counter+1;
+		else
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+			counter=counter+2;
+		end
+	end
+end
+
+if size(tips,1)<2
+	disp('at least one unclosed profile is required')
+	return
+end
+
+%plot the tips only
+plot(tips(:,1),tips(:,2),...
+	'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+firsttip=1;
+
+%loop (at least 2 clicks needed)
+while loop
+
+	%some checks
+	if size(tips,1)<2
+		disp('at least one unclosed profiles are required')
+		return
+	end
+
+	%select a point
+	if firsttip
+		title('click on the first tip, RETURN to exit','FontSize',14)
+	else
+		title('click on the second tip, RETURN to exit','FontSize',14)
+	end
+
+	[xi,yi] = ginput(1);
+
+	if ~isempty(xi)
+
+		if firsttip
+			%find the selected tip
+			distance=(xi-tips(:,1)).^2+(yi-tips(:,2)).^2;
+			[dmin tip1]=min(distance);
+			numprofile1=tips(tip1,3);
+			firsttip=0;
+
+			%remove tip1 from tips list
+			newtips=tips;
+			newtips(tip1,:)=[];
+
+			%plot selected tip
+			plot(tips(tip1,1),tips(tip1,2),...
+				'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(A(numprofile1).x,A(numprofile1).y,...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+
+		%second selection
+		else
+			distance=(xi-newtips(:,1)).^2+(yi-newtips(:,2)).^2;
+			[dmin tip2]=min(distance);
+			numprofile2=newtips(tip2,3);
+
+			if numprofile1==numprofile2
+				%close the profile
+				A(numprofile1).x(end+1)=A(numprofile1).x(1);
+				A(numprofile1).y(end+1)=A(numprofile1).y(1);
+				numpoints=numpoints+1;
+				closed(numprofile1)=1;
+
+			else
+
+				if tips(tip1,4)==1 & newtips(tip2,4)==1,
+					A(numprofile1).x=[flipud(A(numprofile2).x); A(numprofile1).x];
+					A(numprofile1).y=[flipud(A(numprofile2).y); A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==1 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile2).x; A(numprofile1).x];
+					A(numprofile1).y=[A(numprofile2).y; A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==1,
+					A(numprofile1).x=[A(numprofile1).x; A(numprofile2).x];
+					A(numprofile1).y=[A(numprofile1).y; A(numprofile2).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile1).x; flipud(A(numprofile2).x)];
+					A(numprofile1).y=[A(numprofile1).y; flipud(A(numprofile2).y)];
+					numprofiles=numprofiles-1;
+				end
+
+				%delete profile2
+				A(numprofile2)=[];
+				closed(numprofile2)=[];
+
+			end
+
+			%update tips
+			counter=1; tips=[];
+			for i=1:numprofiles
+				if ~closed(i),
+					%x and y coord, profile number, 1 if beginning, 2 and if end
+					if length(A(i).x)==1,
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						counter=counter+1;
+					else
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+						counter=counter+2;
+					end
+				end
+			end
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			if ~isempty(tips)
+				plot(tips(:,1),tips(:,2),...
+					'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			end
+
+			%back to beginning
+			firsttip=1;
+		end
+	else
+		%RETRUN-> quit
+		loop=0;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/modifyposition.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/modifyposition.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/modifyposition.m	(revision 13101)
@@ -0,0 +1,77 @@
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MODIFYPOSITION - modify the prosition of a point of a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting..')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	while loop
+
+		%select a point to be modified 
+		title('click on the point to be modified, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%plot the point in blue
+			plot(A(profsel).x(indsel),A(profsel).y(indsel),...
+				'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%select new location
+			title('click on the new location, RETURN to exit','FontSize',14)
+			[xi,yi] = ginput(1);
+
+			if ~isempty(xi)
+
+				%modification of its coordinates
+				A(profsel).x(indsel)=xi;
+				A(profsel).y(indsel)=yi;
+
+				%modify the last point if the profile is closed and indsel=end or 1
+				if closed(profsel)
+					if indsel==1 
+						A(profsel).x(end)=xi;
+						A(profsel).y(end)=yi;
+					elseif indsel==length(A(profsel).x)
+						A(profsel).x(1)=xi;
+						A(profsel).y(1)=yi;
+					end
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			else
+				%RETURN-> exit
+				loop=0;
+			end
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/orientprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/orientprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/orientprofile.m	(revision 13101)
@@ -0,0 +1,54 @@
+function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ORIENTPROFILE - cahnge profile orientation
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be reoriented, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be reoriented, exiting...')
+			return
+		end
+		   
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from list
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%reorient profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				A(selection(i)).x=flipud(A(selection(i)).x);
+				A(selection(i)).y=flipud(A(selection(i)).y);
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removepoints.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removepoints.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removepoints.m	(revision 13101)
@@ -0,0 +1,85 @@
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPOINTS - remove a point from a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	end
+
+	while loop
+
+		%check that at least one point is present
+		if numpoints==0
+			disp('at least one point are needed')
+			return
+		end	   
+
+		%select a point to be deleted
+		title('click on the point to be removed, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%remove point of A
+			A(profsel).x(indsel)=[];
+			A(profsel).y(indsel)=[];
+
+			%unclose the domain if only 2 points remaining
+			if closed(profsel)
+				if length(A(profsel).x)==3
+					A(profsel).x(end)=[];
+					A(profsel).y(end)=[];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				end
+			end
+
+			%remove the last point if the profile is closed and indsel=end or 1
+			if closed(profsel)
+				if indsel==1 
+					A(profsel).x(end)=A(profsel).x(1);
+					A(profsel).y(end)=A(profsel).y(1);
+				elseif indsel==length(A(profsel).x)
+					A(profsel).x(1)=A(profsel).x(end);
+					A(profsel).y(1)=A(profsel).y(end);
+				end
+			end
+			numpoints=numpoints-1;
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				if length(A(i).x)==1
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+				end
+			end
+
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeprofile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeprofile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeprofile.m	(revision 13101)
@@ -0,0 +1,56 @@
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPROFILE - delete a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be removed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be removed, exiting...')
+			return
+		end
+		   
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%remove the profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				numprofiles=numprofiles-1;
+				numpoints=numpoints-length(A(selection(i)-(i-1)).x);
+				A(selection(i)-(i-1))=[];
+				closed(selection(i)-(i-1))=[];
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeseveralpoints.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeseveralpoints.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/removeseveralpoints.m	(revision 13101)
@@ -0,0 +1,130 @@
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVESEVERALPOINTS - remove several point
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<3
+		disp('at least 3 points are required, exiting...')
+		return
+	end	   
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numpoints<3
+			disp('at least 3 points are required, exiting...')
+			return
+		end
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be removed, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+				%disp(['p1= ' num2str(indsel)]),
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+						%disp(['p2= ' num2str(indsel)]),
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						%disp(['p3= ' num2str(indsel)]),
+						if p1<p2
+							if p3>p1 & p3<p2
+								A(selection).x(p1+1:p2-1)=[];
+								A(selection).y(p1+1:p2-1)=[];
+								numpoints=numpoints-(p2-p1-1);
+							else
+								A(selection).x=A(selection).x(p1:p2);
+								A(selection).y=A(selection).y(p1:p2);
+								numpoints=numpoints-(numpoints-1-p2)-(p1-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						else
+							if p3>p2 & p3<p1
+								A(selection).x(p2+1:p1-1)=[];
+								A(selection).y(p2+1:p1-1)=[];
+								numpoints=numpoints-(p1-p2-1);
+							else
+								A(selection).x=A(selection).x(p2:p1);
+								A(selection).y=A(selection).y(p2:p1);
+								numpoints=numpoints-(numpoints-1-p1)-(p2-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						end
+
+						%plot new profiles
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/undoplots.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/undoplots.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/exp/manipulation/undoplots.m	(revision 13101)
@@ -0,0 +1,12 @@
+function  undoplots(prevplot)
+%UNDOPLOTS - undo plots
+%
+%   Usage:undoplots(prevplot)
+
+	%erase all previous plots
+	g=get(gca,'children');
+	L=length(g);
+	for i=1:L-prevplot
+		delete(g(i));
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/extrusion/DepthAverage.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/extrusion/DepthAverage.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/extrusion/DepthAverage.m	(revision 13101)
@@ -0,0 +1,33 @@
+function  vector_average=DepthAverage(md,vector);
+%DEPTHAVERAGE - computes depth average of 3d vector, and return value on 2d mesh. 
+%
+%   Usage:
+%      vector_average=DepthAverage(md,vector);
+%
+%   Example:
+%      vel_bar=DepthAverage(md,md.initialization.vel);
+
+%check that the model given in input is 3d
+if ~md.mesh.dimension==3;
+	error('DepthAverage error message: the model given in input must be 3d')
+end
+
+%nods data
+if (length(vector)==md.mesh.numberofvertices),
+	vector_average=zeros(md.mesh.numberofvertices2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+(project2d(md,vector,i)+project2d(md,vector,i+1))/2.*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+%element data
+elseif (length(vector)==md.mesh.numberofelements),
+	vector_average=zeros(md.mesh.numberofelements2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+project2d(md,vector,i).*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+else
+	error('vector size not supported yet');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/extrusion/project2d.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/extrusion/project2d.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/extrusion/project2d.m	(revision 13101)
@@ -0,0 +1,36 @@
+function projection_value=project2d(md3d,value,layer)
+%PROJECT2D - returns the value of a field for a given layer of the mesh
+%
+%   project 'value' vector taken at layer 'layer' from extruded 2d-3d mesh onto 2d mesh 
+%   used to do the extrusion. This routine is used to compare values between a 2d-3d mesh
+%   at a certain layer, and the equivalent value (if it exists), on the original 2d mesh. 
+%   This routine relies heavily on projections (contained in 3d model md) recored during 
+%   the extrude operation.
+%
+%   Usage:
+%      projection_value=project2d(md3d,value,layer)
+%
+%   Example:
+%      vel2=project2d(md3d,md3d.vel,2);
+
+%some checks on list of arguments
+if ((nargin~=3) ),
+	help project2d
+	error('project2d error message');
+end
+
+if (md3d.mesh.dimension~=3),
+	error('wrong model type ... should be ''3d''');
+end
+
+if ((layer<1) | (layer>md3d.mesh.numberoflayers)),
+	error(['layer must be between 1 and ' num2str(md3d.mesh.numberoflayers)]);
+end
+
+if size(value,1)==md3d.mesh.numberofvertices,
+	projection_value=value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:);
+elseif size(value,1)==md3d.mesh.numberofvertices+1,
+	projection_value=[value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:); value(end,:)];
+else
+	projection_value=value((layer-1)*md3d.mesh.numberofelements2d+1:layer*md3d.mesh.numberofelements2d,:);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/extrusion/project3d.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/extrusion/project3d.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/extrusion/project3d.m	(revision 13101)
@@ -0,0 +1,82 @@
+function projected_vector=project3d(md,varargin);
+%PROJECT3D - vertically project a vector from 2d mesh
+%
+%   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+%   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+%   element vector of size (md.mesh.numberofelements2d,N/A). 
+%   arguments: 
+%      'vector': 2d vector
+%      'type': 'element' or 'node'. 
+%   options: 
+%      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+%             value of the 2d vector.
+%      'padding': default to 0 (value adopted by other 3d layers not being projected0
+%
+%   Egs:
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node');
+
+%some regular checks
+if nargin==0,
+	help project3d
+	error('bad usage');
+end
+if md.mesh.dimension~=3
+	error('input model is not 3d');
+end
+
+%retrieve parameters from options.
+options      = pairoptions(varargin{:});
+vector2d     = getfieldvalue(options,'vector');     %mandatory
+type         = getfieldvalue(options,'type');       %mandatory
+layer        = getfieldvalue(options,'layer',0);    %optional (do all layers otherwise)
+paddingvalue = getfieldvalue(options,'padding',0);  %0 by default
+
+if length(vector2d)==1,
+	projected_vector=vector2d;
+elseif strcmpi(type,'node'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofvertices2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofvertices2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:md.mesh.numberoflayers,
+			projected_vector(((i-1)*md.mesh.numberofvertices2d+1):(i*md.mesh.numberofvertices2d),:)=vector2d;
+		end
+	else
+		projected_vector(((layer-1)*md.mesh.numberofvertices2d+1):(layer*md.mesh.numberofvertices2d),:)=vector2d;
+	end
+elseif strcmpi(type,'element'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofelements2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofelements2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	if layer==0,
+		for i=1:(md.mesh.numberoflayers-1),
+			projected_vector( ((i-1)*md.mesh.numberofelements2d+1):(i*md.mesh.numberofelements2d),:)=vector2d;
+		end
+
+	else
+		projected_vector( ((layer-1)*md.mesh.numberofelements2d+1):(layer*md.mesh.numberofelements2d),:)=vector2d;
+	end
+else
+	error('project3d error message: unknown projection type');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.m	(revision 13101)
@@ -0,0 +1,57 @@
+function flag=FlagElements(md,region),
+%FLAGELEMENTS - flag the elements in an region
+%
+%   The region can be given with an exp file, a list of elements.
+%
+%   Usage: 
+%      flag=FlagElements(md,region);
+%
+%   Example:
+%      flag=FlagElements(md,'all');
+%      flag=FlagElements(md,'');
+%      flag=FlagElements(md,'Domain.exp');
+%      flag=FlagElements(md,'~Domain.exp');
+%      flag=FlagElements(md,md.mask.elementongroundedice);
+
+	if ischar(region),
+		if isempty(region),
+			flag=zeros(md.mesh.numberofelements,1);
+			invert=0;
+		elseif strcmpi(region,'all')
+			flag=ones(md.mesh.numberofelements,1);
+			invert=0;
+		else
+			%make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region(1),'~'),
+				region=region(2:length(region));
+				invert=1;
+			else
+				invert=0;
+			end
+
+			%does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if ~exist(region,'file'),
+				if (length(region)>3 & ~strcmp(region(end-3),'.exp')),
+					error(['Error: File ' region ' not found!']);
+				end
+				[xlim,ylim]=basinzoom('basin',region);
+				flag_nodes=double(md.mesh.x<xlim(2) & md.mesh.x>xlim(1) &  md.mesh.y<ylim(2) & md.mesh.y>ylim(1));
+				flag=prod(flag_nodes(md.mesh.elements),2);
+			else
+				%ok, flag elements
+				flag=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,region,'element',1);
+			end
+		end
+		if invert,
+			flag=~flag;
+		end
+	elseif isfloat(region) | islogical(region),
+		if size(region,1)~=md.mesh.numberofelements,
+			help FlagElements
+			error('Flaglist for region must be of same size as number of elements in model');
+		end
+		flag=region;
+	else
+		error('Invalid region option');
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/FlagElements.py	(revision 13101)
@@ -0,0 +1,62 @@
+import numpy
+import os
+#from basinzoom import *
+#from ContourToMesh import *
+from MatlabFuncs import *
+
+def FlagElements(md,region):
+	"""
+	FLAGELEMENTS - flag the elements in an region
+
+	   The region can be given with an exp file, a list of elements.
+
+	   Usage: 
+	      flag=FlagElements(md,region);
+
+	   Example:
+	      flag=FlagElements(md,'all');
+	      flag=FlagElements(md,'');
+	      flag=FlagElements(md,'Domain.exp');
+	      flag=FlagElements(md,'~Domain.exp');
+	      flag=FlagElements(md,md.mask.elementongroundedice);
+	"""
+
+	if   isinstance(region,(str,unicode)):
+		if   not region:
+			flag=numpy.zeros(md.mesh.numberofelements,'bool')
+			invert=0
+		elif strcmpi(region,'all'):
+			flag=numpy.ones(md.mesh.numberofelements,'bool')
+			invert=0
+		else:
+			#make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region[0],'~'):
+				region=region[1:]
+				invert=1
+			else:
+				invert=0
+
+			#does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if not os.path.exists(region):
+				if len(region)>3 and not strcmp(region[-4:],'.exp'):
+					raise IOError("Error: File 'region' not found!" % region)
+				xlim,ylim=basinzoom('basin',region)
+				flag_nodes=numpy.logical_and(numpy.logical_and(md.mesh.x<xlim[1],md.mesh.x>xlim[0]),numpy.logical_and(md.mesh.y<ylim[1],md.mesh.y>ylim[0])).astype(float)
+				flag=numpy.prod(flag_nodes[md.mesh.elements],axis=1)
+			else:
+				#ok, flag elements
+				flag=ContourToMesh(md.mesh.elements[:,0:3],md.mesh.x,md.mesh.y,region,'element',1)
+
+		if invert:
+			flag=numpy.logical_not(flag)
+
+	elif isinstance(region,numpy.nparray) or isinstance(region,bool):
+		if not numpy.size(region,0)==md.mesh.numberofelements:
+			raise TypeError("Flaglist for region must be of same size as number of elements in model.")
+		flag=region
+
+	else:
+		raise TypeError("Invalid region option")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/GetAreas.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/GetAreas.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/GetAreas.m	(revision 13101)
@@ -0,0 +1,51 @@
+function areas=GetAreas(index,x,y,varargin)
+%GETAREAS - compute areas or volumes of elements
+%
+%   compute areas of triangular elements or volumes 
+%   of pentahedrons
+%
+%   Usage:
+%      areas  =GetAreas(index,x,y);
+%      volumes=GetAreas(index,x,y,z);
+%
+%   Examples:
+%      areas  =GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+%      volumes=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y,md.z);
+
+%get number of elements and number of nodes
+nels=size(index,1);
+nods=length(x);
+if nargin==4, z=varargin{1}; end
+
+%some checks
+if nargout~=1 | (nargin~=3 & nargin~=4),
+	help GetAreas
+	error('GetAreas error message: bad usage')
+end
+if ((length(y)~=nods) | (nargin==4 & length(z)~=nods)),
+	error('GetAreas error message: x,y and z do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetAreas error message: index should not have values above ' num2str(nods) ])
+end
+if (nargin==3 & size(index,2)~=3),
+	error('GetAreas error message: index should have 3 columns for 2d meshes.')
+end
+if (nargin==4 & size(index,2)~=6),
+	error('GetAreas error message: index should have 6 columns for 3d meshes.')
+end
+
+%initialization
+areas=zeros(nels,1);
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+
+%compute the volume of each element
+if nargin==3,
+	%compute the surface of the triangle
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+else
+	%V=area(triangle)*1/3(z1+z2+z3)
+	thickness=mean(z(index(:,4:6)),2)-mean(z(index(:,1:3)),2);
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1))).*thickness;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/SegIntersect.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/SegIntersect.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/SegIntersect.m	(revision 13101)
@@ -0,0 +1,79 @@
+function bool=SegIntersect(seg1,seg2)
+%SEGINTERSECT - test of segments intersection
+%
+%   return 1 if the two segments intersect
+%   seg1=[x1 y1; x2 y2]
+%   seg2=[x1 y1; x2 y2]
+%
+%   Usage:
+%      bool=SegIntersect(seg1,seg2)
+
+bool=1;
+
+xA=seg1(1,1); yA=seg1(1,2);
+xB=seg1(2,1); yB=seg1(2,2);
+xC=seg2(1,1); yC=seg2(1,2);
+xD=seg2(2,1); yD=seg2(2,2);
+
+O2A=[xA;yA]-[xD/2+xC/2;yD/2+yC/2];
+O2B=[xB;yB]-[xD/2+xC/2;yD/2+yC/2];
+O1C=[xC;yC]-[xA/2+xB/2;yB/2+yA/2];
+O1D=[xD;yD]-[xA/2+xB/2;yB/2+yA/2];
+
+n1=[yA-yB;xB-xA]; %normal vector to segA
+n2=[yC-yD;xD-xC]; %normal vectot to segB
+
+test1=n2'*O2A;
+test2=n2'*O2B;
+
+if test1*test2>0
+	bool=0;
+	return;
+end
+
+test3=n1'*O1C;
+test4=n1'*O1D;
+
+if test3*test4>0
+	bool=0;
+	return;
+end
+
+%if colinear
+if test1*test2==0 & test3*test4==0 & det([n1 n2])==0
+
+	%projection on the axis O1O2
+	O2O1=[xA/2+xB/2;yB/2+yA/2]-[xD/2+xC/2;yD/2+yC/2];
+	O1A=O2O1'*(O2A-O2O1);
+	O1B=O2O1'*(O2B-O2O1);
+	O1C=O2O1'*O1C;
+	O1D=O2O1'*O1D;
+	
+	%test if one point is included in the other segment (->bool=1)
+	if (O1C-O1A)*(O1D-O1A)<0
+		bool=1;
+		return;
+	end
+	if (O1C-O1B)*(O1D-O1B)<0
+		bool=1;
+		return;
+	end
+	if (O1A-O1C)*(O1B-O1C)<0
+		bool=1;
+		return;
+	end
+	if (O1A-O1D)*(O1B-O1D)<0
+		bool=1;
+		return;
+	end
+
+	 %test if the 2 segments have the same middle (->bool=1)
+	if O2O1==0
+		bool=1;
+		return;
+	end
+
+	%else
+	bool=0;
+	return;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/ThicknessCorrection.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/ThicknessCorrection.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/ThicknessCorrection.m	(revision 13101)
@@ -0,0 +1,77 @@
+function md=ThicknessCorrection(md,varargin)
+%THICKNESSCORRECTION - correct the thickness of the ice shelf near the grounding line
+%
+%   This routine corrects the thickness and the bed on the transition zone
+%   by forcing the hydrostatic equilibrium.
+%   the thickness is modified as follows:
+%      thickness = (1-coeff) * thickness_observation + coeff * thickness_hydrostatic
+%   where:
+%      coeff=(d/distance)^2;
+%      distance=10km by default but can be specified
+%
+%   Usage:
+%      md=ThicknessCorrection(md,varargin);
+%
+%   Example:
+%      md=ThicknessCorrection(md);
+%      md=ThicknessCorrection(md,15000);
+
+%initialize thickness with the observations, and get hydrostatic thickness from the dem
+thickness=md.geometry.thickness;
+thickness_hydro=md.geometry.surface/(1-md.materials.rho_ice/md.materials.rho_water);
+hydrostatic_ratio=zeros(size(md.geometry.thickness));
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+debug=(length(pos_shelf)>50000);
+
+%check that there is a GL
+if isempty(pos_GL)
+	error('ThicknessCorrection error message: no grounding line has been detected. Check the model mask');
+end
+
+%get distance
+if nargin==2,
+	distance=varargin{1};
+else
+	distance=10000;
+end
+
+%modify thickness
+if (debug), fprintf('%s','      correction progress:   0.00 %'); end
+for i=1:length(pos_shelf)
+
+	if (debug & mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d>distance,
+
+		%if d > 15km, hydrostatic equilibrium
+		hydrostatic_ratio(pos_shelf(i))=1;
+		thickness(pos_shelf(i))=thickness_hydro(pos_shelf(i));
+
+	else
+
+		%else: quadratic combination of hydrostatic equilibrium and observations
+		hydrostatic_ratio(pos_shelf(i))=(d/distance)^2;
+		thickness(pos_shelf(i))=(1-hydrostatic_ratio(pos_shelf(i)))*thickness(pos_shelf(i))+hydrostatic_ratio(pos_shelf(i))*thickness_hydro(pos_shelf(i));
+
+	end
+end
+if (debug), fprintf('\b\b\b\b\b\b\b%5.2f%s\n',100,' %'); end
+
+%check the computed thickness
+minth=1/(1-md.materials.rho_ice/md.materials.rho_water);
+pos=find(isnan(thickness) | (thickness<=0));
+thickness(pos)=minth;
+hydrostatic_ratio(pos)=-1;
+
+%change bed to take into account the changes in thickness
+md.geometry.thickness=thickness;
+md.geometry.hydrostatic_ratio=hydrostatic_ratio;
+md.geometry.bed=md.geometry.surface-md.geometry.thickness;
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/find_point.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/find_point.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/find_point.m	(revision 13101)
@@ -0,0 +1,14 @@
+function f=find_point(tabx,taby,pointx,pointy)
+%FIND_POINT - find closest point
+%
+%   find which point of the list (tabx,taby) is
+%   the closest to (poinx,pointy)
+%
+%   Usage:
+%      f=find_point(tabx,taby,pointx,pointy)
+
+%Compute distance between point and cloud of points
+distance=sqrt((tabx-pointx).^2+(taby-pointy).^2);
+
+%find index of the minimum distance and return the first one only
+f=find(distance==min(min(distance)),1);
Index: /issm/branches/trunk-jpl-damage/src/m/geometry/slope.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/geometry/slope.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/geometry/slope.m	(revision 13101)
@@ -0,0 +1,32 @@
+function [sx,sy,s]=slope(md)
+%SLOPE - compute the surface slope
+%
+%   Usage:
+%      [sx,sy,s]=slope(md)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+sx=(md.geometry.surface(index).*alpha)*summation;
+sy=(md.geometry.surface(index).*beta)*summation;
+s=sqrt(sx.^2+sy.^2);
+
+if md.mesh.dimension==3,
+	sx=project3d(md,'vector',sx,'type','element');
+	sy=project3d(md,'vector',sy,'type','element');
+	s=sqrt(sx.^2+sy.^2);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/interp/InterpFromFile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/InterpFromFile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/InterpFromFile.m	(revision 13101)
@@ -0,0 +1,200 @@
+function data_out=InterpFromFile(x,y,filename,default_value)
+%INTERPFROMFILE - load data and interpolate on the given nodes
+%
+%   load a matlab file (extension .mat) which holds 3 or 4 variables
+%   and interpolate the data on the mesh and plug it onto the model.
+%
+%   o 3 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a vector or matrix data (if the name of the variable do not begin with the field name, an error can appear)
+%   o 4 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a matrix with 3 columns (if the name of the variable do not begin with "index" or "elements", an error can appear)
+%     - a vector data (if the name of the variable do not begin with the field name, an error can appear)
+%
+%   Usage:
+%      data=InterpFromFile(x,y,filename,default_value);
+%
+%   Example:
+%      md.geometry.surface=InterpFromFile(md.mesh.x,md.mesh.y,'surfacefile.mat',0);
+%
+%   See also: PLUGVELOCITIES, INTERPFROMGRID, INTERPFROMMESH2D, INTERPFROMMESH3D
+
+%some checks
+if nargin~=4 | nargout~=1
+	help InterpFromFile
+	error('plugdata error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugdata error message: file ' filename  ' does not exist']);
+end
+if length(x)~=length(y),
+	error('plugdata error message: x and y should have the same length');
+end
+
+%load file
+Names=FieldFindVarNames(filename);
+Data=load(filename);
+if strcmpi(Names.interp,'node'),
+	data_out=InterpFromGridToMesh(Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y,default_value);
+else
+	data_out=InterpFromMeshToMesh2d(Data.(Names.indexname),Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y);
+end
+
+end
+function Names=FieldFindVarNames(filename)
+%FIELDFINDVARNAMES - find names of variables in a data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,data)
+%   or (index,x,y,data)
+%
+%   Usage:
+%      Names=FieldFindVarNames(filename)
+%
+%   Example:
+%      Names=FieldFindVarNames('thickness.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help FieldFindVarNames
+	error('FieldFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['FieldFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; dataenum=NaN; indexenum=NaN;
+if length(A)==3,
+	isnode=1;
+	for i=1:3
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+elseif length(A)==4,
+	isnode=0;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,'index',5) | strncmpi(A(i).name,'elements',7));
+			indexenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+else
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (it should hold 3 variables x,y and data (for nodes) OR 4 variables  x,y,index and data (for mesh))']);
+end
+
+%2: if only one item is missing, find it by elimination
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%assum that we have found at least xenum and yenum
+if ( isnan(xenum) | isnan(yenum))
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (the coordinates vectors should be named x and y)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:4
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['FieldFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%4: last chance
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%last check
+if isnan(dataenum)
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (data not found)']);
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.dataname=A(dataenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/interp/PatchToVec.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/PatchToVec.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/PatchToVec.m	(revision 13101)
@@ -0,0 +1,21 @@
+function vec=PatchToVec(Patch);
+%PATCHTOVEC - converts a patch to a vector by averaging over each vertex
+%
+%   Usage:
+%      vec=PatchToVec(Patch)
+
+%if the patch is P0: we have element values, return an element vector
+switch(size(Patch.value,2)),
+	case 1,
+		vec(Patch.element)=Patch.value;
+	case 3,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	case 6,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	otherwise,
+		error('interpolation not supported yet');
+	end
Index: /issm/branches/trunk-jpl-damage/src/m/interp/ProfileValues.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/ProfileValues.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/ProfileValues.m	(revision 13101)
@@ -0,0 +1,21 @@
+function [Z,data_interp]=ProfileValues(md,data,xprof,yprof,resolution)
+%PROFILEVALUES - compute the value of a field on a vertical profile
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [z,data]=ProfileValues(md,data,filename,resolution)
+%      [z,data]=ProfileValues(md,data,profile_structure,resolution)
+
+%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+offset=10^-3;
+bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.bed,1),xprof,yprof)+offset;
+surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),xprof,yprof)-offset;
+
+%Some useful parameters
+layers=ceil(mean(md.geometry.thickness)/resolution);
+Z=(bed:resolution:surface)';
+X=xprof*ones(size(Z));
+Y=yprof*ones(size(Z));
+data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X,Y,Z,NaN);
Index: /issm/branches/trunk-jpl-damage/src/m/interp/SectionValues.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/SectionValues.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/SectionValues.m	(revision 13101)
@@ -0,0 +1,127 @@
+function [index,X,Y,Z,S,data_interp]=SectionValues(md,data,infile,resolution)
+%SECTIONVALUES - compute the value of a field on a section
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [elements,x,y,z,s,data]=SectionValues(md,data,filename,resolution)
+%      [elements,x,y,z,s,data]=SectionValues(md,data,profile_structure,resolution)
+
+%check what we have for profile as input
+if ischar(infile),
+	%read infile:
+	profile=expread(infile);
+	nods=profile.nods;
+	x=profile.x;
+	y=profile.y;
+else
+	%read infile:
+	nods=infile.nods;
+	x=infile.x;
+	y=infile.y;
+end
+
+
+%get the specified resolution
+if isnumeric(resolution(1))
+	res_h=resolution(1);
+else
+	error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+end
+if md.mesh.dimension==3
+	if (length(resolution)==2 & isnumeric(resolution(2)))
+		res_v=resolution(2);
+	else
+		error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+	end
+end
+
+%initialization
+X=[]; %X-coordinate
+Y=[]; %Y-coordinate
+S=0;  %curvilinear coordinate
+
+for i=1:nods-1
+
+	x_start=x(i);
+	x_end=x(i+1);
+	y_start=y(i);
+	y_end=y(i+1);
+	s_start=S(end);
+
+	length_segment=sqrt((x_end-x_start)^2+(y_end-y_start)^2);
+	portion=ceil(length_segment/res_h);
+
+	x_segment=zeros(portion,1);
+	y_segment=zeros(portion,1);
+	s_segment=zeros(portion,1);
+
+	for j=1:portion
+		x_segment(j)=x_start+(j-1)*(x_end-x_start)/portion;
+		y_segment(j)=y_start+(j-1)*(y_end-y_start)/portion;
+		s_segment(j)=s_start+j*length_segment/portion;
+	end
+
+	%plug into X and Y
+	X=[X;x_segment];
+	Y=[Y;y_segment];
+	S=[S;s_segment];
+end
+X(end+1)=x(nods);
+Y(end+1)=y(nods);
+
+%Number of nodes:
+numberofnodes=size(X,1);
+
+%Compute Z
+Z=zeros(numberofnodes,1);
+
+%New mesh and Data interpolation
+if (md.mesh.dimension==2)
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=griddata(md.mesh.x,md.mesh.y,data,X,Y);
+
+	%Compute index
+	index=[1:1:(numberofnodes-1);2:1:numberofnodes]';
+
+else
+
+	%vertically extrude mesh
+
+	%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+	offset=10^-3;
+	bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.bed,1),X,Y)+offset;
+	surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),X,Y)-offset;
+
+	%Some useful parameters
+	layers=ceil(mean(md.geometry.thickness)/res_v);
+	nodesperlayer=numberofnodes;
+	nodestot=nodesperlayer*layers;
+	elementsperlayer=nodesperlayer-1;
+	elementstot=(nodesperlayer-1)*(layers-1);
+
+	%initialization
+	X3=zeros(nodesperlayer*layers,1); Y3=zeros(nodesperlayer*layers,1); Z3=zeros(nodesperlayer*layers,1); S3=zeros(nodesperlayer*layers,1); index3=zeros(elementstot,4);
+
+	%Get new coordinates in 3d
+	for i=1:layers
+		X3(i:layers:end)=X;
+		Y3(i:layers:end)=Y;
+		Z3(i:layers:end)=bed+(i-1)*(surface-bed)/(layers-1);
+		S3(i:layers:end)=S;
+
+		if i<layers %Build index3 with quads
+			index3((i-1)*elementsperlayer+1:i*elementsperlayer,:)=[i:layers:nodestot-layers; i+1:layers:nodestot-layers; i+layers+1:layers:nodestot; i+layers:layers:nodestot]';
+		end
+	end
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,NaN);
+
+	%build outputs
+	X=X3; Y=Y3; Z=Z3;  S=S3; index=index3;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/interp/averaging.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/averaging.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/averaging.m	(revision 13101)
@@ -0,0 +1,90 @@
+function average=averaging(md,data,iterations,varargin)
+%AVERAGING - smooths the input over the mesh
+%
+%   This routine takes a list over the elements or the nodes in input
+%   and return a list over the nodes.
+%   For each iterations it computes the average over each element (average 
+%   of the vertices values) and then computes the average over each node
+%   by taking the average of the element around a node weighted by the
+%   elements volume
+%   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
+%
+%   Usage:
+%      smoothdata=averaging(md,data,iterations)
+%      smoothdata=averaging(md,data,iterations,layer)
+%
+%   Examples:
+%      velsmoothed=averaging(md,md.initialization.vel,4);
+%      pressure=averaging(md,md.initialization.pressure,0);
+%      temperature=averaging(md,md.initialization.temperature,1,1);
+
+if ((nargin~=4) & (nargin~=3)),
+	error('averaging error message');
+end
+if (length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices),
+	error('averaging error message: data not supported yet');
+end
+if md.mesh.dimension==3 & nargin==4,
+	if varargin{1}<=0 | varargin{1}>md.mesh.numberoflayers,
+		error('layer should be between 1 and md.mesh.numberoflayers');
+	end
+	layer=varargin{1};
+else
+	layer=0;
+end
+
+%initialization
+if layer==0,
+	weights=zeros(md.mesh.numberofvertices,1);
+	data=data(:);
+else 
+	weights=zeros(md.mesh.numberofvertices2d,1);
+	data=data((layer-1)*md.mesh.numberofvertices2d+1:layer*md.mesh.numberofvertices2d,:);
+end
+
+%load some variables (it is much faster if the variabes are loaded from md once for all)
+if layer==0,
+	index=md.mesh.elements;
+	numberofnodes=md.mesh.numberofvertices;
+	numberofelements=md.mesh.numberofelements;
+else
+	index=md.mesh.elements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	numberofelements=md.mesh.numberofelements2d;
+end
+
+%build some variables
+line=index(:);
+if md.mesh.dimension==3 & layer==0,
+	rep=6;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z);
+elseif md.mesh.dimension==2,
+	rep=3;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y);
+else
+	rep=3;
+	areas=GetAreas(index,md.mesh.x2d,md.mesh.y2d);
+end
+summation=1/rep*ones(rep,1);
+linesize=rep*numberofelements;
+
+%update weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,rep,1),numberofnodes,1);
+
+%initialization
+if length(data)==numberofelements
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*data,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+else
+	average_node=data;
+end
+
+%loop over iteration
+for i=1:iterations
+	average_el=average_node(index)*summation;
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*average_el,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+end
+
+%return output as a full matrix (C code do not like sparse matrices)
+average=full(average_node);
Index: /issm/branches/trunk-jpl-damage/src/m/interp/plugvelocities.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/interp/plugvelocities.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/interp/plugvelocities.m	(revision 13101)
@@ -0,0 +1,166 @@
+function md=plugvelocities(md,filename,default_value)
+%PLUGVELOCITIES - load velocities on a model
+%
+%   load a matlab file (extension .mat) which holds 4 variables
+%   x,y,vx,vy to be plugged onto the model (or similar names)
+%   x and y must be vectors, vx, vy matrices
+%
+%   Usage:
+%      md=plugvelocities(md,filename,default_value)
+%
+%   Example:
+%      md=plugvelocities(md,'velocityfile.mat',0);
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+disp('WARNING: deprecated functions (plugvelocities)');
+%some checks
+if nargin~=3 | nargout~=1
+	help plugvelocities
+	error('plugvelocities error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugvelocities error message: file ' filename  ' does not exist']);
+end
+
+%load velocities 
+Names=VelFindVarNames(filename);
+Vel=load(filename);
+
+%Interpolation
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+end
+
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx=md.inversion.vx_obs;
+md.initialization.vy=md.inversion.vy_obs;
+md.initialization.vel=md.inversion.vel_obs;
+end
+
+function Names=VelFindVarNames(filename)
+%VELFINDVARNAMES - find names of variables in a velocity data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,vx,vy)
+%   or (index,x,y,vx,vy)
+%
+%   Usage:
+%      Names=VelFindVarNames(filename)
+%
+%   Example:
+%      Names=VelFindVarNames('velocities.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help VelFindVarNames
+	error('VelFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['VelFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; vxenum=NaN; vyenum=NaN; indexenum=NaN;
+if length(A)==4,
+	isnode=1;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+elseif length(A)==5,
+	isnode=0;
+	for i=1:5
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strcmpi(A(i).name(1),'index') | strcmpi(A(i).name(1),'elements'));
+			indexenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+else
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (it should hold 4 variables x,y,vx and vy (for nodes) OR 5 variables  x,y,index,vx and vy (for mesh))']);
+end
+
+%assum that we have found at least vxenum and vyenum
+if ( isnan(vxenum) | isnan(vyenum))
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (the velocities should be named vx and vy)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:5
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['VelFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%find x y
+if (isnan(xenum) | isnan(yenum))
+
+	%check the size
+	if A(vxenum).size(1)==A(vxenum).size(2),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (velocities is a square matrix, save x and y with another name)']);
+	end
+	if ~(A(vxenum).size(1)==A(vyenum).size(1) & A(vxenum).size(2)==A(vyenum).size(2)),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (vx and vy matrices do not have the same size)']);
+	end
+
+	%find xenum and yenum
+	for i=1:4
+		lengthi=max(A(i).size);
+		if ((i~=vxenum) & (lengthi==A(vxenum).size(1) | lengthi==A(vxenum).size(1)+1)),
+			yenum=i;
+		elseif ((i~=vxenum) & (lengthi==A(vxenum).size(2) | lengthi==A(vxenum).size(2)+1)),
+			xenum=i;
+		end
+	end
+
+	%last check
+	if (isnan(xenum) | isnan(yenum))
+		error(['plugdata error message: file ' filename  ' not supported yet']);
+	end
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.vxname=A(vxenum).name;
+Names.vyname=A(vyenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
Index: /issm/branches/trunk-jpl-damage/src/m/inversions/MisfitDeinterlace.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/inversions/MisfitDeinterlace.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/inversions/MisfitDeinterlace.m	(revision 13101)
@@ -0,0 +1,21 @@
+function Jstruct=MisfitDeinterlace(misfit,type)
+%MISFITDEINTERLACE - deinterlace misfits that are mixed together, using type.
+%
+%   Usage:
+%      Jstruct=MisfitDeinterlace(misfit,type)
+%
+%   Example:
+%      Jstruct=MisfitDeinterlace(md.results.diagnostic.J,md.fit)
+%
+%
+Jstruct=struct();
+
+count=1;
+for i=0:max(type),
+	pos=find(type==i);
+	if length(pos),
+		Jstruct(count).type=i;
+		Jstruct(count).J=misfit(pos);
+		count=count+1;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/inversions/misfit.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/inversions/misfit.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/inversions/misfit.m	(revision 13101)
@@ -0,0 +1,37 @@
+function J=misfit(md)
+%MISFIT - compute misfit
+%
+%   Usage:
+%      J=misfit(md)
+%
+%   Example:
+%      J=misfit(md)
+%
+
+if md.mesh.dimension==2,
+	elements=md.mesh.elements;
+	x=md.mesh.x;
+	y=md.mesh.y;
+	vx=md.initialization.vx;
+	vy=md.initialization.vy;
+	vx_obs=md.inversion.vx_obs;
+	vy_obs=md.inversion.vy_obs;
+else
+	elements=md.mesh.elements2d;
+	x=md.mesh.x2d;
+	y=md.mesh.y2d;
+	vx=project2d(md,md.initialization.vx,md.mesh.numberoflayers);
+	vy=project2d(md,md.initialization.vy,md.mesh.numberoflayers);
+	vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
+	vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
+end
+
+%compute areas;
+areas=GetAreas(elements,x,y);
+
+%compute delta v on elements
+deltav=1/2*(   (vx-vx_obs).^2+(vy-vy_obs).^2)/md.constants.yts^2;
+deltav_elem=deltav(elements)*[1;1;1]/3;
+
+%compute misfit
+J=sum(deltav_elem.*areas);
Index: /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontrolB.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontrolB.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontrolB.m	(revision 13101)
@@ -0,0 +1,122 @@
+function md=parametercontrolB(md,varargin),
+%PARAMETERCONTROLB - parameterization for control method on B
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of B, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontrolB(md,varargin)
+%
+%   Example:
+%      md=parametercontrolB(md)
+%      md=parametercontrolB(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontrolB(md,'cm_min',10,'cm_max',10^8,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontrolB(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also  PARAMETERCONTROLDRAG
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',paterson(273.15+5)*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',paterson(273.15-70)*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.9*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.9*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[ 101:105])),
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[2*10^8*ones(3,1);10^8*ones(third-3,1);10^7*ones(2*third,1);];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontroldrag.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontroldrag.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/inversions/parametercontroldrag.m	(revision 13101)
@@ -0,0 +1,121 @@
+function md=parametercontroldrag(md,varargin),
+%PARAMETERCONTROLDRAG - parameterization for control method on drag
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of the drag, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontroldrag(md,varargin)
+%
+%   Example:
+%      md=parametercontroldrag(md)
+%      md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also PARAMETERCONTROLB
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'FrictionCoefficient'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',1*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',250*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.8*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.8*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[101 105]))
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/branches/trunk-jpl-damage/src/m/io/loadmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/io/loadmodel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/io/loadmodel.m	(revision 13101)
@@ -0,0 +1,46 @@
+function varargout=loadmodel(path)
+%LOADMODEL - load a model using built-in load module
+%
+%   check that model prototype has not changed. if so, adapt to new model prototype.
+%
+%   Usage:
+%      md=loadmodel(path)
+%      loadmodel path
+
+%check nargout
+if nargout>1,
+	error('loadmodel usage error: md=loadmodel(path)');
+end
+
+%check existence
+if exist(path,'file')
+	%do nothing
+elseif exist([path '.mat'],'file')
+	%add extension
+	path = [path '.mat'];
+else
+	error(['loadmodel error message: file ' path ' does not exist']);
+end
+
+try,
+	%recover model on file and name it md
+	warning off MATLAB:unknownElementsNowStruc;
+	warning off MATLAB:load:classNotFound
+	struc=load(path,'-mat');
+	warning on MATLAB:unknownElementsNowStruc;
+	warning on MATLAB:load:classNotFound
+
+	name=char(fieldnames(struc));
+	if size(name,1)>1,
+		error(['loadmodel error message: file ' path ' contains several variables. Only one model should be present.']); 
+	end
+	md=struc.(name);
+	if nargout,
+		varargout{1}=md;
+	else
+		assignin('caller',name,md);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/io/loadmodellist.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/io/loadmodellist.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/io/loadmodellist.m	(revision 13101)
@@ -0,0 +1,50 @@
+function varargout=loadmodellist(path)
+%LOADMODELLIST- load a model using built-in load module
+%
+%   check that modellist prototype has not changed. if so, adapt to new modellist prototype.
+%
+%   Usage:
+%      mds=loadmodellist(path)
+%      loadmodellist path
+
+%check nargout
+if nargout>1,
+	error('loadmodellist usage error: mds=loadmodellist(path)');
+end
+%check existence
+if ~exist(path)
+	error(['loadmodellist error message: file ' path ' does not exist']);
+end
+
+%check that the file is readable
+[stat,mess]=fileattrib(path);
+if( stat==0 | mess.UserRead~=1),
+	error(['loadmodellist error message: file ' path ' is not readable (permission dinied).']);
+end
+
+%check number of variables
+if length(whos('-file',path))>1,
+	error(['loadmodellist error message: file ' path ' contains several variables. Only one model should be present.']);
+end
+
+try,
+	struc=load(path,'-mat');
+
+	%get name of model variable
+	fieldname=char(fieldnames(struc));
+	mds=eval(['struc.' fieldname]);
+	if ~strcmpi(class(mds),'model'),
+		mds2=modellist;
+		mds2=structtomodel(mds2,mds);
+		mds=mds2;
+		clear mds2;
+	end
+	if nargout,
+		varargout{1}=mds;
+	else
+		assignin('caller',fieldname,mds);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/kml/exp2kml.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/kml/exp2kml.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/kml/exp2kml.m	(revision 13101)
@@ -0,0 +1,19 @@
+function exp2kml(input,output)
+%EXP2KML: transform Argus exp file to kml
+%
+% Usage:    exp2kml('temp.exp','temp2.kml')
+%
+%
+
+
+%First, read exp file
+domain=expread(input);
+
+
+%then transform: 
+string=ge_plot(domain.x,domain.y,'name',domain.name);
+
+%open kml file for writing: 
+fid=fopen(output,'w');
+fprintf(fid,'%s',string);
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/kml/kml2exp.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/kml/kml2exp.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/kml/kml2exp.m	(revision 13101)
@@ -0,0 +1,29 @@
+function kml2exp(input,output)
+%KML2EXP: transform kml file Argus exp file.
+%
+% Usage:    kmltoexp('temp.kml','temp2.exp')
+%
+%
+
+
+
+
+%First, read polygon kml file.
+structure=kml_shapefile(input);
+	
+%create exp file: 
+domain=struct();
+for i=1:length(structure),
+
+	if isfield(structure,'name'),
+		domain(end+1).name=structure(i).name;
+	else
+		domain(end+1).name='NaN';
+	end
+
+	domain(end).density=1;
+	domain(end).x=structure(i).X;
+	domain(end).y=structure(i).Y;
+end
+domain=domain(2:end);
+expwrite(domain,output);
Index: /issm/branches/trunk-jpl-damage/src/m/kml/kml2expg.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/kml/kml2expg.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/kml/kml2expg.m	(revision 13101)
@@ -0,0 +1,13 @@
+function kml2expg(filename)
+
+	[path,name,ext]=fileparts(filename);
+
+	if strcmpi(ext,'.kmz'),
+		eval(['!unzip ' filename]);
+		eval(['!mv doc.kml ' name '.kml']);
+		kml2exp([name '.kml'],[name '.exp']);
+		expll2xy([name '.exp'],1);
+	end
+
+	kml2exp([name '.kml'],[name '.exp']);
+	expll2xy([name '.exp'],1);
Index: /issm/branches/trunk-jpl-damage/src/m/kml/kmlimagesc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/kml/kmlimagesc.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/kml/kmlimagesc.m	(revision 13101)
@@ -0,0 +1,67 @@
+function kmlimagesc(md,fieldname,varargin)
+%KMLIMAGESC - create lat,long kml image
+%
+%   Usage:
+%      kmlimagesc(md,field,options);
+%
+%   Options: 
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%      'posting': default .1 degree
+%
+
+%process varargin for options: 
+options=pairoptions(varargin{:});
+
+%recover field: 
+field=md.(fieldname);
+
+%recover some options, and set defaults
+fontsize=getfieldvalue(options,'fontsize',12);
+posting=getfieldvalue(options,'posting',.1);
+minlong=getfieldvalue(options,'minlong',min(md.mesh.long));
+maxlong=getfieldvalue(options,'maxlong',max(md.mesh.long));
+minlat=getfieldvalue(options,'minlat',min(md.mesh.lat));
+maxlat=getfieldvalue(options,'maxlat',max(md.mesh.lat));
+minfield=getfieldvalue(options,'minfield',min(field));
+maxfield=getfieldvalue(options,'maxfield',max(field));
+
+%do we have hemisphere setup?:
+if ~isstr(md.mesh.hemisphere),
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+if strcmpi(md.mesh.hemisphere,'s'),
+	hemisphere=1;
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+elseif strcmpi(md.mesh.hemisphere,'n'),
+	hemisphere=-1;
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+else
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+%figure out nlines and ncols in our image
+nlines=(maxlat-minlat)/posting;
+ncols=(maxlong-minlong)/posting;
+
+%regrid to lat,long grid
+[x_m,y_m,field]=InterpFromMeshToGrid(md.mesh.elements,md.mesh.long,md.mesh.lat,field,minlong,maxlat,posting,posting,nlines,ncols,NaN);
+field=flipud(field);
+
+%massage  and log:
+pos=find(field<minfield); field(pos)=minfield;
+pos=find(field>maxfield);field(pos)=maxfield;
+
+%create google earth kml file out of this regridded dataset:
+imagestr=ge_imagesc(x_m,y_m,field,'imgURL',[fieldname '.png'],'name',fieldname);
+imagestr=ge_folder(fieldname,imagestr);
+colorbarstr=ge_colorbar((min(x_m)+max(x_m))/2,(min(y_m)+max(y_m))/2,field,'name',fieldname);
+colorbarstr=ge_folder('Colorbar',colorbarstr);
+ge_output([fieldname '.kml'],[imagestr colorbarstr]);
+
+%now, create kmz file:
+system(['mv ' [fieldname '.kml'] ' doc.kml && zip ' [fieldname '.kmz'] ' doc.kml ' fieldname '.png && rm -rf doc.kml ' [fieldname '.png'] ]);
Index: /issm/branches/trunk-jpl-damage/src/m/latlong/ll2xy.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/latlong/ll2xy.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/latlong/ll2xy.m	(revision 13101)
@@ -0,0 +1,66 @@
+function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help ll2xy
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+latitude  = abs(lat) * pi/180.;
+longitude = (lon + delta) * pi/180.;
+
+% compute X and Y in grid coordinates.
+T = tan(pi/4-latitude/2) ./ ((1-ex*sin(latitude))./(1+ex*sin(latitude))).^(ex/2);
+
+if (90 - slat) <  1.e-5 
+	rho = 2.*re*T/sqrt((1.+ex)^(1.+ex)*(1.-ex)^(1.-ex));
+else
+	sl  = slat*pi/180.;
+	tc  = tan(pi/4.-sl/2.)/((1.-ex*sin(sl))/(1.+ex*sin(sl)))^(ex/2.);
+	mc  = cos(sl)/sqrt(1.0-ex2*(sin(sl)^2));
+	rho = re*mc*T/tc;
+end
+
+y = -rho .* sgn .* cos(sgn.*longitude);
+x =  rho .* sgn .* sin(sgn.*longitude);
+
+[cnt1,cnt2] = find(latitude >= pi / 2.);
+
+if cnt1
+	x(cnt1,1) = 0.0;
+	y(cnt1,1) = 0.0;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/latlong/utm2ll.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/latlong/utm2ll.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/latlong/utm2ll.m	(revision 13101)
@@ -0,0 +1,117 @@
+function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
+% -------------------------------------------------------------------------
+% [Lat,Lon] = utm2ll(x,y,utmzone)
+%
+% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
+% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%
+% Inputs:on)
+%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%
+% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
+% [Lat, Lon]=utm2ll(x,y,utmzone);
+% LatDMS=dms2mat(deg2dms(Lat))
+%LatDMS =
+%    40.00         18.00         55.55
+%    46.00         17.00          2.01
+%    37.00         34.00         40.17
+%    28.00         38.00         44.33
+%    38.00         51.00         19.96
+%    25.00          3.00         42.41
+% LonDMS=dms2mat(deg2dms(Lon))
+%LonDMS =
+%    -3.00         29.00          8.61
+%     7.00         48.00          4.40
+%  -119.00         57.00         18.93
+%   -17.00         45.00         34.33
+%   -94.00         47.00         56.47
+%   121.00         38.00         24.96
+%
+% Author:
+%   Rafael Palacios
+%   Universidad Pontificia Comillas
+%   Madrid, Spain
+% Version: Apr/06, Jun/06, Aug/06
+% Aug/06: corrected m-Lint warnings
+%-------------------------------------------------------------------------
+
+% Argument checking
+%
+error(nargchk(3, 3, nargin)); %3 arguments required
+n1=length(xx);
+n2=length(yy);
+n3=size(utmzone,1);
+if (n1~=n2 || n1~=n3)
+	error('x,y and utmzone vectors should have the same number or rows');
+end
+c=size(utmzone,2);
+if (c~=4)
+	error('utmzone should be a vector of strings like "30 T"');
+end
+
+% Memory pre-allocation
+%
+Lat=zeros(n1,1);
+Lon=zeros(n1,1);
+
+% Main Loop
+%
+for i=1:n1
+	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
+		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+	end
+	if (utmzone(i,4)>'M')
+		hemis='N';   % Northern hemisphere
+	else
+		hemis='S';
+	end
+
+	x=xx(i);
+	y=yy(i);
+	zone=str2double(utmzone(i,1:2));
+
+	sa = 6378137.000000 ; sb = 6356752.314245;
+
+	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
+	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
+	e2cuadrada = e2 ^ 2;
+	c = ( sa ^ 2 ) / sb;
+	%   alpha = ( sa - sb ) / sa;             %f
+	%   ablandamiento = 1 / alpha;   % 1/f
+
+	X = x - 500000;
+
+	if hemis == 'S' || hemis == 's'
+		Y = y - 10000000;
+	else
+		Y = y;
+	end
+
+	S = ( ( zone * 6 ) - 183 );
+	lat =  Y / ( 6366197.724 * 0.9996 );
+	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
+	a = X / v;
+	a1 = sin( 2 * lat );
+	a2 = a1 * ( cos(lat) ) ^ 2;
+	j2 = lat + ( a1 / 2 );
+	j4 = ( ( 3 * j2 ) + a2 ) / 4;
+	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
+	alfa = ( 3 / 4 ) * e2cuadrada;
+	beta = ( 5 / 3 ) * alfa ^ 2;
+	gama = ( 35 / 27 ) * alfa ^ 3;
+	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
+	b = ( Y - Bm ) / v;
+	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
+	Eps = a * ( 1 - ( Epsi / 3 ) );
+	nab = ( b * ( 1 - Epsi ) ) + lat;
+	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
+	Delt = atan(senoheps / (cos(nab) ) );
+	TaO = atan(cos(Delt) * tan(nab));
+	longitude = (Delt *(180 / pi ) ) + S;
+	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
+		(180 / pi);
+
+	Lat(i)=latitude;
+	Lon(i)=longitude;
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/latlong/xy2ll.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/latlong/xy2ll.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/latlong/xy2ll.m	(revision 13101)
@@ -0,0 +1,72 @@
+function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2ll
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+sl  = slat*pi/180.;
+rho = sqrt(x.^2 + y.^2);
+cm = cos(sl) / sqrt(1.0 - ex2 * (sin(sl)^2));
+T = tan((pi / 4.0) - (sl / 2.0)) / ((1.0 - ex * sin(sl)) / (1.0 + ex * sin(sl)))^(ex / 2.0);
+
+if  abs(slat-90.) < 1.e-5
+	T = rho * sqrt((1. + ex)^(1. + ex) * (1. - ex)^(1. - ex)) / 2. / re;
+else
+	T = rho * T / (re * cm);
+end
+
+chi = (pi / 2.0) - 2.0 * atan(T);
+lat = chi + ((ex2 / 2.0) + (5.0 * ex2^2.0 / 24.0) + (ex2^3.0 / 12.0)) * ...
+	sin(2 * chi) + ((7.0 * ex2^2.0 / 48.0) + (29.0 * ex2^3 / 240.0)) * ...
+	sin(4.0 * chi) + (7.0 * ex2^3.0 / 120.0) * sin(6.0 * chi) ;
+
+lat = sgn * lat;
+lon = atan2(sgn * x,-sgn * y);
+lon = sgn * lon;
+
+[res1,res2] = find(rho <= 0.1);
+if res1
+	lat(res1,1) = 90. * sgn;
+	lon(res1,1) = 0.0;
+end
+
+lon = lon * 180. / pi;
+lat = lat * 180. / pi;
+lon = lon - delta; 
Index: /issm/branches/trunk-jpl-damage/src/m/materials/paterson.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/materials/paterson.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/materials/paterson.m	(revision 13101)
@@ -0,0 +1,42 @@
+function rigidity=paterson(temperature)
+%PATERSON - figure out the rigidity of ice for a given temperature
+%
+%   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+%   temperature is in Kelvin degrees
+%
+%   Usage:
+%      rigidity=paterson(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+%The routine below is equivalent to:
+
+% n=3; T=temperature-273;
+% %From paterson,
+% Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+% A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+% 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+% %Convert into rigidity B
+% B=A.^(-1/n)*10^3; %s^(1/3)Pa
+% %Now, do a cubic fit between Temp and B: 
+% fittedmodel=fit(Temp,B,'cubicspline');
+% rigidity=fittedmodel(temperature);
+
+rigidity=zeros(length(T),1);
+pos1=find(T<=-45);           rigidity(pos1)=10^8*(-0.000292866376675*(T(pos1)+50).^3+ 0.011672640664130*(T(pos1)+50).^2  -0.325004442485481*(T(pos1)+50)+  6.524779401948101);
+pos2=find(-45<=T & T<-40);   rigidity(pos2)=10^8*(-0.000292866376675*(T(pos2)+45).^3+ 0.007279645014004*(T(pos2)+45).^2  -0.230243014094813*(T(pos2)+45)+  5.154964909039554);
+pos3=find(-40<=T & T<-35);   rigidity(pos3)=10^8*(0.000072737147457*(T(pos3)+40).^3+  0.002886649363879*(T(pos3)+40).^2  -0.179411542205399*(T(pos3)+40)+  4.149132666831214);
+pos4=find(-35<=T & T<-30);   rigidity(pos4)=10^8*(-0.000086144770023*(T(pos4)+35).^3+ 0.003977706575736*(T(pos4)+35).^2  -0.145089762507325*(T(pos4)+35)+  3.333333333333331);
+pos5=find(-30<=T & T<-25);   rigidity(pos5)=10^8*(-0.000043984685769*(T(pos5)+30).^3+ 0.002685535025386*(T(pos5)+30).^2  -0.111773554501713*(T(pos5)+30)+  2.696559088937191);
+pos6=find(-25<=T & T<-20);   rigidity(pos6)=10^8*(-0.000029799523463*(T(pos6)+25).^3+ 0.002025764738854*(T(pos6)+25).^2  -0.088217055680511*(T(pos6)+25)+  2.199331606342181);
+pos7=find(-20<=T & T<-15);   rigidity(pos7)=10^8*(0.000136920904777*(T(pos7)+20).^3+  0.001578771886910*(T(pos7)+20).^2  -0.070194372551690*(T(pos7)+20)+  1.805165505978111);
+pos8=find(-15<=T & T<-10);   rigidity(pos8)=10^8*(-0.000899763781026*(T(pos8)+15).^3+ 0.003632585458564*(T(pos8)+15).^2  -0.044137585824322*(T(pos8)+15)+  1.510778053489523);
+pos9=find(-10<=T & T<-5);    rigidity(pos9)=10^8*(0.001676964325070*(T(pos9)+10).^3-  0.009863871256831*(T(pos9)+10).^2  -0.075294014815659*(T(pos9)+10)+  1.268434288203714);
+pos10=find(-5<=T & T<-2);    rigidity(pos10)=10^8*(-0.003748937622487*(T(pos10)+5).^3+0.015290593619213*(T(pos10)+5).^2  -0.048160403003748*(T(pos10)+5)+  0.854987973338348);
+pos11=find(-2<=T);           rigidity(pos11)=10^8*(-0.003748937622488*(T(pos11)+2).^3-0.018449844983174*(T(pos11)+2).^2  -0.057638157095631*(T(pos11)+2)+  0.746900791092860);
+
+%Now make sure that rigidity is positive
+pos=find(rigidity<0);        rigidity(pos)=10^6;
Index: /issm/branches/trunk-jpl-damage/src/m/materials/paterson.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/materials/paterson.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/materials/paterson.py	(revision 13101)
@@ -0,0 +1,50 @@
+from numpy import *
+
+def paterson(temperature):
+
+    # Local Variables: pos11, pos5, pos10, temperature, pos, T, pos8, pos9, pos6, pos7, pos4, rigidity, pos2, pos3, pos1
+    # Function calls: length, zeros, argwhere, paterson, error
+    #PATERSON - figure out the rigidity of ice for a given temperature
+    #
+    #   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+    #   temperature is in Kelvin degrees
+    #
+    #   Usage:
+    #      rigidity=paterson(temperature)
+    
+	pos=argwhere(temperature<0.)
+	if len(pos):
+		print 'input temperature should be in Kelvin (positive)'
+		return []
+    
+	T = temperature-273.15
+	#The routine below is equivalent to:
+	# n=3; T=temperature-273;
+	# %From paterson,
+	# Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+	# A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+	# 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+	# %Convert into rigidity B
+	# B=A.^(-1/n)*10^3; %s^(1/3)Pa
+	# %Now, do a cubic fit between Temp and B: 
+	# fittedmodel=fit(Temp,B,'cubicspline');
+	# rigidity=fittedmodel(temperature);
+
+	rigidity=zeros(len(T))
+	pos1=argwhere(T<=-45);           rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
+	pos2=argwhere(logical_and(-45<=T,T<-40));   rigidity[pos2]=10**8*(-0.000292866376675*(T[pos2]+45)**3+ 0.007279645014004*(T[pos2]+45)**2  -0.230243014094813*(T[pos2]+45)+  5.154964909039554)
+	pos3=argwhere(logical_and(-40<=T,T<-35));   rigidity[pos3]=10**8*(0.000072737147457*(T[pos3]+40)**3+  0.002886649363879*(T[pos3]+40)**2  -0.179411542205399*(T[pos3]+40)+  4.149132666831214)
+	pos4=argwhere(logical_and(-35<=T,T<-30));   rigidity[pos4]=10**8*(-0.000086144770023*(T[pos4]+35)**3+ 0.003977706575736*(T[pos4]+35)**2  -0.145089762507325*(T[pos4]+35)+  3.333333333333331)
+	pos5=argwhere(logical_and(-30<=T,T<-25));   rigidity[pos5]=10**8*(-0.000043984685769*(T[pos5]+30)**3+ 0.002685535025386*(T[pos5]+30)**2  -0.111773554501713*(T[pos5]+30)+  2.696559088937191)
+	pos6=argwhere(logical_and(-25<=T,T<-20));   rigidity[pos6]=10**8*(-0.000029799523463*(T[pos6]+25)**3+ 0.002025764738854*(T[pos6]+25)**2  -0.088217055680511*(T[pos6]+25)+  2.199331606342181)
+	pos7=argwhere(logical_and(-20<=T,T<-15));   rigidity[pos7]=10**8*(0.000136920904777*(T[pos7]+20)**3+  0.001578771886910*(T[pos7]+20)**2  -0.070194372551690*(T[pos7]+20)+  1.805165505978111)
+	pos8=argwhere(logical_and(-15<=T,T<-10));   rigidity[pos8]=10**8*(-0.000899763781026*(T[pos8]+15)**3+ 0.003632585458564*(T[pos8]+15)**2  -0.044137585824322*(T[pos8]+15)+  1.510778053489523)
+	pos9=argwhere(logical_and(-10<=T,T<-5));    rigidity[pos9]=10**8*(0.001676964325070*(T[pos9]+10)**3-  0.009863871256831*(T[pos9]+10)**2  -0.075294014815659*(T[pos9]+10)+  1.268434288203714)
+	pos10=argwhere(logical_and(-5<=T,T<-2));    rigidity[pos10]=10**8*(-0.003748937622487*(T[pos10]+5)**3+0.015290593619213*(T[pos10]+5)**2  -0.048160403003748*(T[pos10]+5)+  0.854987973338348)
+	pos11=argwhere(-2<=T);           rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2  -0.057638157095631*(T[pos11]+2)+  0.746900791092860)
+
+	#Now make sure that rigidity is positive
+	pos=argwhere(rigidity<0);        rigidity[pos]=1**6 
+
+	return rigidity
+
Index: /issm/branches/trunk-jpl-damage/src/m/meca/basalstress.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/meca/basalstress.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/meca/basalstress.m	(revision 13101)
@@ -0,0 +1,22 @@
+function [bx by b]=basalstress(md)
+%BASALSTRESS - compute basal stress from basal drag and geometric information. 
+%
+%   Usage:
+%      [bx by b]=basalstress(md);
+%
+%   See also: plot_basaldrag
+
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+ubx=md.initialization.vx/md.constants.yts;
+uby=md.initialization.vy/md.constants.yts;
+
+%compute basal drag
+bx=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ubx.^s;
+by=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*uby.^s;
+b=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ub.^s;
Index: /issm/branches/trunk-jpl-damage/src/m/meca/cfl_step.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/meca/cfl_step.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/meca/cfl_step.m	(revision 13101)
@@ -0,0 +1,23 @@
+function maxtime=cfl_step(md,vx,vy);
+%CFL_STEP - return the maximum time step for the model in years
+%
+%   Dt < 0.5 / ( u/Dx +v/Dy )
+%
+%   Usage:
+%      maxtime=cfl_step(md,vx,vy);
+%
+%   Example:
+%      dt=cfl_step(md,md.results.DiagnosticSolution.Vx,md.results.DiagnosticSolution.Vy)
+
+%Check length of velocities 
+if size(vx,1)~=md.mesh.numberofvertices & size(vy,1)~=md.mesh.numberofvertices,
+	error('timestpes error message: size of velocity components must be the same as md.mesh.numberofvertices');
+end
+
+index=md.mesh.elements;
+edgex=max(md.mesh.x(index),[],2)-min(md.mesh.x(index),[],2);
+edgey=max(md.mesh.y(index),[],2)-min(md.mesh.y(index),[],2);
+vx=max(abs(vx(index)),[],2);
+vy=max(abs(vy(index)),[],2);
+
+maxtime=1/2*min(1./(vx./edgex+vy./edgey));
Index: /issm/branches/trunk-jpl-damage/src/m/meca/drivingstress.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/meca/drivingstress.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/meca/drivingstress.m	(revision 13101)
@@ -0,0 +1,18 @@
+function [px,py,pmag]=drivingstress(md)
+%DRIVINGSTRESS -  evaluates the driving stress
+%
+%   The driving stress is computed according to the following formula: 
+%   driving stress= rho_ice*g*H*slope
+%
+%   Usage:
+%      [Fx,Fy,Fmag]=drivingstress(md)
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness over elements
+thickness_bar=(md.geometry.thickness(md.mesh.elements(:,1))+md.geometry.thickness(md.mesh.elements(:,2))+md.geometry.thickness(md.mesh.elements(:,3)))/3;
+
+px=md.materials.rho_ice*md.constants.g*thickness_bar.*sx;
+py=md.materials.rho_ice*md.constants.g*thickness_bar.*sy;
+pmag=sqrt(px.^2+py.^2);
Index: /issm/branches/trunk-jpl-damage/src/m/meca/mechanicalproperties.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/meca/mechanicalproperties.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/meca/mechanicalproperties.m	(revision 13101)
@@ -0,0 +1,118 @@
+function md=mechanicalproperties(md,vx,vy)
+%MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+%
+%   this routine computes the components of the stress tensor
+%   strain rate tensor and their respective principal directions.
+%   the results are in the model md: md.results
+%
+%   Usage:
+%      md=mechanicalproperties(md,vx,vy)
+%
+%   Example:
+%      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy);
+%      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs);
+
+%some checks
+if length(vx)~=md.mesh.numberofvertices | length(vy)~=md.mesh.numberofvertices,
+	error(['the input velocity should be of size ' num2str(md.mesh.numberofvertices) '!'])
+end
+if ~(md.mesh.dimension==2)
+	error('only 2d model supported yet');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non macayeal elements. These will be treated like MacAyeal''s elements');
+end
+
+%initialization
+numberofelements=md.mesh.numberofelements;
+index=md.mesh.elements;
+summation=[1;1;1];
+directionsstress=zeros(numberofelements,4);
+directionsstrain=zeros(numberofelements,4);
+valuesstress=zeros(numberofelements,2);
+valuesstrain=zeros(numberofelements,2);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y);
+
+%compute shear
+vxlist=vx(index)/md.constants.yts;
+vylist=vy(index)/md.constants.yts;
+ux=(vxlist.*alpha)*summation;
+uy=(vxlist.*beta)*summation;
+vx=(vylist.*alpha)*summation;
+vy=(vylist.*beta)*summation;						
+uyvx=(vx+uy)./2;
+clear vxlist vylist
+
+%compute viscosity
+nu=zeros(numberofelements,1);
+B_bar=md.materials.rheology_B(index)*summation/3;
+power=(md.materials.rheology_n-1)./(2*md.materials.rheology_n);
+second_inv=(ux.^2+vy.^2+((uy+vx).^2)/4+ux.*vy);
+%some corrections
+location=find(second_inv~=0);
+nu(location)=B_bar(location)./(second_inv(location).^power(location));
+location=find(second_inv==0 & power~=0);
+nu(location)=10^18; 	%arbitrary maximum viscosity to apply where there is no effective shear
+location=find(second_inv==0 & power==0);
+nu(location)=B_bar(location);
+clear B_bar location second_inv power
+
+%compute stress
+tau_xx=nu.*ux;
+tau_yy=nu.*vy;
+tau_xy=nu.*uyvx;
+
+%compute principal properties of stress
+for i=1:numberofelements,
+
+	%compute stress and strainrate matrices
+	stress=[tau_xx(i) tau_xy(i)
+	tau_xy(i)  tau_yy(i)];
+	strain=[ux(i) uyvx(i)
+	uyvx(i)  vy(i)];
+
+	%eigen values and vectors
+	[directions,value]=eig(stress);
+	valuesstress(i,:)=[value(1,1) value(2,2)];
+	directionsstress(i,:)=directions(:)';
+	[directions,value]=eig(strain);
+	valuesstrain(i,:)=[value(1,1) value(2,2)];
+	directionsstrain(i,:)=directions(:)';
+end
+
+%plug onto the model
+%NB: Matlab sorts the eigen value in increasing order, we want the reverse
+stress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+stress.xx=tau_xx;
+stress.yy=tau_yy;
+stress.xy=tau_xy;
+stress.principalvalue2=valuesstress(:,1);
+stress.principalaxis2=directionsstress(:,1:2);
+stress.principalvalue1=valuesstress(:,2);
+stress.principalaxis1=directionsstress(:,3:4);
+stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.stress=stress;
+
+strainrate=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+strainrate.xx=ux;
+strainrate.yy=vy;
+strainrate.xy=uyvx;
+strainrate.principalvalue2=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis2=directionsstrain(:,1:2);
+strainrate.principalvalue1=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis1=directionsstrain(:,3:4);
+strainrate.effectivevalue=1/sqrt(2)*sqrt(strainrate.xx.^2+strainrate.yy.^2+2*strainrate.xy.^2);
+md.results.strainrate=strainrate;
+
+deviatoricstress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+deviatoricstress.xx=tau_xx;
+deviatoricstress.yy=tau_yy;
+deviatoricstress.xy=tau_xy;
+deviatoricstress.principalvalue2=valuesstress(:,1);
+deviatoricstress.principalaxis2=directionsstress(:,1:2);
+deviatoricstress.principalvalue1=valuesstress(:,2);
+deviatoricstress.principalaxis1=directionsstress(:,3:4);
+deviatoricstress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.deviatoricstress=deviatoricstress;
Index: /issm/branches/trunk-jpl-damage/src/m/meca/shear2d.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/meca/shear2d.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/meca/shear2d.m	(revision 13101)
@@ -0,0 +1,23 @@
+function [sx,sy,sxy,s]=shear2d(md)
+%SHEAR2D - computes 2d strain rate
+%
+%   This routine computes the strain rate of 2d models
+%
+%   Usage:
+%      [sx,sy,sxy,s]=shear2d(md);
+%      s=shear2d(md);
+
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+summation=[1;1;1];
+sx=(md.initialization.vx(md.mesh.elements).*alpha)*summation;
+uy=(md.initialization.vx(md.mesh.elements).*beta)*summation;
+vx=(md.initialization.vy(md.mesh.elements).*alpha)*summation;
+sy=(md.initialization.vy(md.mesh.elements).*beta)*summation;						
+sxy=(uy+vx)/2;
+s=sqrt(sx.^2+sy.^2+sxy.^2+sx.*sy);
+
+%if user requested only one output, it must be the norm
+if nargout==1,
+	sx=s;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeHessian.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeHessian.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeHessian.m	(revision 13101)
@@ -0,0 +1,60 @@
+function hessian=ComputeHessian(index,x,y,field,type)
+%COMPUTEHESSIAN - compute hessian matrix from a field
+%
+%   Compute the hessian matrix of a given field
+%   return the three components Hxx Hxy Hyy
+%   for each element or each node
+%
+%   Usage:
+%      hessian=ComputeHessian(index,x,y,field,type)
+%
+%   Example:
+%      hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vel_obs,'node')
+
+%some variables
+numberofnodes=length(x);
+numberofelements=size(index,1);
+
+%some checks
+if length(field)~=numberofnodes & length(field)~=numberofelements,
+	error('ComputeHessian error message: the given field size not supported yet');
+end
+if strcmpi(type,'node') & strcmpi(type,'element'),
+	error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
+end
+
+%initialization
+line=index(:);
+linesize=3*numberofelements;
+
+%get areas and  nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+areas=GetAreas(index,x,y);
+
+%comput weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,3,1),numberofnodes,1);
+
+%compute field on nodes if on elements
+if length(field)==numberofelements,
+	field=sparse(line,ones(linesize,1),repmat(areas.*field,3,1),numberofnodes,1)./weights ;
+end
+
+%Compute gradient for each element
+grad_elx=sum(field(index).*alpha,2); 
+grad_ely=sum(field(index).*beta,2);
+
+%Compute gradient for each node (average of the elements around)
+gradx=sparse(line,ones(linesize,1),repmat(areas.*grad_elx,3,1),numberofnodes,1);
+grady=sparse(line,ones(linesize,1),repmat(areas.*grad_ely,3,1),numberofnodes,1);
+gradx=gradx./weights;
+grady=grady./weights;
+
+%Compute hessian for each element
+hessian=[sum(gradx(index).*alpha,2) sum(grady(index).*alpha,2) sum(grady(index).*beta,2)];
+
+if strcmpi(type,'node')
+	%Compute Hessian on the nodes (average of the elements around)
+	hessian=[sparse(line,ones(linesize,1),repmat(areas.*hessian(:,1),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,2),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,3),3,1),numberofnodes,1)./weights ];
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeMetric.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeMetric.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/ComputeMetric.m	(revision 13101)
@@ -0,0 +1,66 @@
+function metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%COMPUTEMETRIC - compute metric from an Hessian
+%
+%   Usage:
+%      metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%      pos is contains the positions where the metric is wished to be maximized (water?)
+%
+%   Example:
+%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
+
+%first, find the eigen values of eah line of H=[hessian(i,1) hessian(i,2); hessian(i,2)  hessian(i,3)]
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+pos1=find(lambda1==0);
+pos2=find(lambda2==0);
+pos3=find(b==0 & lambda1==lambda2);
+
+%Modify the eigen values to control the shape of the elements
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+%compute eigen vectors
+norm1=sqrt(8*b.^2+2*(d-a).^2+2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v1x=2*b./norm1;
+v1y=((d-a)+sqrt((a-d).^2+4*b.^2))./norm1;
+norm2=sqrt(8*b.^2+2*(d-a).^2-2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v2x=2*b./norm2;
+v2y=((d-a)-sqrt((a-d).^2+4*b.^2))./norm2;
+
+v1x(pos3)=1; v1y(pos3)=0;
+v2x(pos3)=0; v2y(pos3)=1;
+
+%Compute new metric (for each node M=V*Lambda*V^-1)
+metric=full([(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v2y.*v1x-lambda2.*v1y.*v2x) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v1y.*v2y-lambda2.*v1y.*v2y) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(-lambda1.*v2x.*v1y+lambda2.*v1x.*v2y)]);
+
+%some corrections for 0 eigen values
+metric(pos1,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos1),1);
+metric(pos2,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos2),1);
+
+%take care of water elements
+metric(pos,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos),1);
+
+%take care of NaNs if any (use Matlab eig in a loop)
+[pos posj]=find(isnan(metric)); clear posj;
+if ~isempty(pos),
+	fprintf(' %i %s',length(pos),'NaN found in the metric. Use Matlab routine...');
+	for i=1:length(pos)
+		H=[hessian(pos(i),1) hessian(pos(i),2)
+		hessian(pos(i),2) hessian(pos(i),3)];
+		[u,v]=eig(full(H));
+		lambda1=v(1,1);
+		lambda2=v(2,2);
+		v(1,1)=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+		v(2,2)=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+		metricTria=u*v*u^(-1);
+		metric(pos(i),:)=[metricTria(1,1) metricTria(1,2) metricTria(2,2)];
+	end
+end
+
+if any(isnan(metric)),
+	error('ComputeMetric error message: NaN in the metric despite our efforts...')
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/ElementsFromEdge.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/ElementsFromEdge.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/ElementsFromEdge.m	(revision 13101)
@@ -0,0 +1,15 @@
+function edgeelements=ElementsFromEdge(elements,A,B) 
+%ELEMENTSFROMEDGE: find elements connected to one edge defined by nodes A and B
+%
+% Usage: edgeelements=ElementsFromEdge(elements,A,B) 
+%
+% Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
+%
+%
+edgeelements=find(...
+(elements(:,1)==A & elements(:,2)==B )| ...
+(elements(:,1)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,2)==B ));
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/FixMesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/FixMesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/FixMesh.m	(revision 13101)
@@ -0,0 +1,45 @@
+function  [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+% FIXMESH - FixMesh fix mesh with broken triangles, orphan vertices, etc ...
+%
+%   Usage: 
+%      [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+%      where index,x,y is a delaunay triangulation, 
+%      value is a field on the input triangulation, with values at the vertices
+%      index2,x2,y2,value2 is the repaired triangulation, with new values on new vertices
+%
+%
+
+%duplicate inputs
+index2=index;
+x2=x;
+y2=y;
+value2=value;
+
+%First, look for orphan vertices, and take them out.
+flags=zeros(length(x2),1); flags(index2)=1;
+orphans=find(flags==0);
+
+while ~isempty(orphans),
+
+	%take the first orphan, the lower numbered, and take it out
+	orphan=orphans(1);
+
+	%first x,y,value
+	x2(orphan)=[];
+	y2(orphan)=[];
+	value2(orphan)=[];
+
+	%now, the index:
+	pos=find(index2>orphan); index2(pos)=index2(pos)-1;
+	
+	%look again for orphans on new mesh
+	flags=zeros(length(x2),1);flags(index2)=1;
+	orphans=find(flags==0);
+end
+
+%Check all triangles are well oriented.
+aires=GetAreas(index2,x2,y2);
+pos=find(aires<0);
+temp=index2(pos,1);
+index2(pos,1)=index2(pos,2);
+index2(pos,2)=temp;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/GetNodalFunctionsCoeff.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 13101)
@@ -0,0 +1,56 @@
+function [alpha beta varargout]=GetNodalFunctionsCoeff(index,x,y)
+%GETNODELFUNCTIONSCOEFF - compute nodal functions coefficients
+%
+%   Compute the coefficients alpha beta and optionaly gamma of
+%   2d triangular elements. For each element, the nodal function
+%   is defined as:
+%   N(x,y)=sum(i=1:3) alpha_i * x + beta_i * y + gamma_i
+%
+%   Usage:
+%      [alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(index,x,y);
+%
+%   Example:
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%make columns out of x and y
+x=x(:); y=y(:);
+
+%get nels and nods
+nels=size(index,1);
+nods=length(x);
+
+%some checks
+if nargin~=3 | (nargout~=2 & nargout~=3),
+	help GetNodalFunctionsCoeff
+	error('GetNodalFunctionsCoeff error message: bad usage')
+end
+if length(y)~=nods,
+	error('GetNodalFunctionsCoeff error message: x and y do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetNodalFunctionsCoeff error message: index should not have values above ' num2str(nods) ])
+end
+if size(index,2)~=3,
+	error('GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.')
+end
+
+%initialize output
+alpha=zeros(nels,3);
+beta=zeros(nels,3);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+invdet=1./(x1.*(y2-y3)-x2.*(y1-y3)+x3.*(y1-y2));
+
+%get alpha and beta
+alpha=[invdet.*(y2-y3) invdet.*(y3-y1) invdet.*(y1-y2)];
+beta =[invdet.*(x3-x2) invdet.*(x1-x3) invdet.*(x2-x1)];
+
+%get gamma if requested
+if nargout==3,
+	gamma=zeros(nels,3);
+	gamma=[invdet.*(x2.*y3-x3.*y2) invdet.*(y1.*x3-y3.*x1) invdet.*(x1.*y2-x2.*y1)];
+	varargout{1}=gamma;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/MergeMetrics.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/MergeMetrics.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/MergeMetrics.m	(revision 13101)
@@ -0,0 +1,15 @@
+function metric=MergeMetrics(metric1,metric2)
+
+M1xx=metric1(:,1); M1xy=metric1(:,2); M1yy=metric1(:,3);
+M1lambda1=0.5*((M1xx+M1yy)+sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+M1lambda2=0.5*((M1xx+M1yy)-sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+lambda1=min(M1lambda1,M1lambda2);
+
+M2xx=metric1(:,1); M2xy=metric1(:,2); M2yy=metric1(:,3);
+M2lambda1=0.5*((M2xx+M2yy)+sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+M2lambda2=0.5*((M2xx+M2yy)-sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+lambda2=min(M2lambda2,M2lambda2);
+
+metric=metric1;
+pos=find(lambda2<lambda1);
+metric(pos,:)=metric2(pos,:);
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/MeshQuality.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/MeshQuality.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/MeshQuality.m	(revision 13101)
@@ -0,0 +1,82 @@
+function quality=MeshQuality(md,epsilon,hmin,hmax);
+%MESHQUALITY - compute mesh quality
+%
+%   Usage:
+%      MeshQuality(md,epsilon,hmin,hmax);
+
+%Get some variables from the model
+index=md.mesh.elements;
+x=md.mesh.x;
+y=md.mesh.y;
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+hessian=ComputeHessian(index,x,y,md.inversion.vel_obs,'node');
+
+%Compute metric
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+
+%Get Areas
+areas=GetAreas(index,x,y);
+
+%length edges vectors
+e1x=[x(index(:,2))-x(index(:,1))];
+e1y=[y(index(:,2))-y(index(:,1))];
+e2x=[x(index(:,3))-x(index(:,2))];
+e2y=[y(index(:,3))-y(index(:,2))];
+e3x=[x(index(:,1))-x(index(:,3))];
+e3y=[y(index(:,1))-y(index(:,3))];
+
+%metric of each the 3 nodes for each element
+M1=metric(index(:,1),:);
+M2=metric(index(:,2),:);
+M3=metric(index(:,3),:);
+
+%Get edge length in the metric
+L1=1/2*(sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y))+sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y)));
+L2=1/2*(sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y))+sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y)));
+L3=1/2*(sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y))+sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y)));
+
+%area in the metric
+V=1/3*areas.*(sqrt(M1(:,1).*M1(:,3)-M1(:,2).^2)+sqrt(M2(:,1).*M2(:,3)-M2(:,2).^2)+sqrt(M3(:,1).*M3(:,3)-M3(:,2).^2));
+
+%compute quality:
+quality=4*sqrt(3)*V./(L1+L2+L3);
+
+%compute error
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+a=a(index)*[1;1;1]/3;
+b=b(index)*[1;1;1]/3;
+d=d(index)*[1;1;1]/3;
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+if length(md.nodeonwater)==md.mesh.numberofvertices;
+	pos=find(md.nodeonwater);
+	lambda1(pos)=0;
+	lambda2(pos)=0;
+end
+lambda1=lambda1(index)*[1;1;1]/3;
+lambda2=lambda2(index)*[1;1;1]/3;
+
+lambdamax=max(lambda1,lambda2);
+hmax=max(max(sqrt(e1x.^2+e1y.^2),sqrt(e2x.^2+e2y.^2)),sqrt(e3x.^2+e3y.^2));
+epsilon=scale*hmax.^2.*lambdamax;
+
+%display
+%X=0:0.1:4; hist(quality,X); xlim([0 3]); title('mesh quality distribution','FontSize',14);
+%plotmodel(md,'data',epsilon,'title','Interpolation error','figure',2)
+disp(sprintf('\n%s','Mesh Quality'));
+disp(sprintf('   %s %g','Average Mesh quality: ',mean(quality)));
+disp(sprintf('   %s %g','Worst Element quality:',max(quality)));
+disp(sprintf('\n%s','Interpolation Error'));
+disp(sprintf('   %s %g %s','Average interpolation error:',mean(epsilon),'m/yr'));
+disp(sprintf('   %s %g %s','Maximum interpolation error:',max(epsilon),'m/yr'));
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/NodeInElement.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/NodeInElement.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/NodeInElement.m	(revision 13101)
@@ -0,0 +1,42 @@
+function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity);
+% NODEINELEMENT - find for a list of nodes (in newx,newy), which elements in the mesh (elements,x,y) they belong to.
+%
+%    Usage:
+%      node_in_element=NodeInElement(newx,newy,elements,x,y,md.mesh.vertexconnectivity);
+%
+%  See also Nodeconnectivity
+%
+epsilon=10^-10;
+
+%compute some quantities that will speed up the process
+x3x1=x(elements(:,1))-x(elements(:,3));
+y3y1=y(elements(:,1))-y(elements(:,3));
+x3x2=x(elements(:,2))-x(elements(:,3));
+y3y2=y(elements(:,2))-y(elements(:,3));
+x3=x(elements(:,3));
+y3=y(elements(:,3));
+delta=x(elements(:,2)).*y(elements(:,3))-y(elements(:,2)).*x(elements(:,3))-x(elements(:,1)).*y(elements(:,3))+y(elements(:,1)).*x(elements(:,3))+x(elements(:,1)).*y(elements(:,2))-y(elements(:,1)).*x(elements(:,2));
+
+%max connectivity:
+max_connectivity=max(nodeconnectivity(:,end));
+node_in_element=zeros(length(newx),max_connectivity+1); %last column is the number of elements to which the row node is connected.
+
+for i=1:length(newx),
+	x0=newx(i);
+	y0=newy(i);
+	
+	%first area coordinate
+	area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
+	%second area coordinate
+	area_2=(x3x1.*(y0-y3)-y3y1.*(x0-x3))./delta;
+	%third area coordinate
+	area_3=1-area_1-area_2;
+	
+	%get elements for which all area coordinates are positive (meaning (x0,y0) belongs to these elements
+	pos=find((area_1>=0-epsilon) & (area_2>=0-epsilon) & (area_3>=0-epsilon));
+
+	num_elements=length(pos);
+
+	node_in_element(i,1:num_elements)=pos;
+	node_in_element(i,end)=num_elements;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/ProfileProjectOntoMesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/ProfileProjectOntoMesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/ProfileProjectOntoMesh.m	(revision 13101)
@@ -0,0 +1,66 @@
+function mesh_profile=ProfileProjectOntoMesh(md,profile)
+%PROFILEPROJECTONTOMESH: project a profile (made of arbitrary points) onto a mesh, so that we end 
+%                        up with a list of segments self contained onto elements.
+%
+% Usage: mesh_profile=ProfileProjectOntoMesh(md,profile)
+%
+% See also intersections.m
+
+%make a curve out of the mesh, to use the intersections routine.
+rows=[md.mesh.elements md.mesh.elements(:,1)]'; rows=rows(:);
+x=md.mesh.x(rows);
+y=md.mesh.y(rows);
+
+%[x0,y0] = intersections(profile.x,profile.y,x,y,1);
+[x0,y0,indices,j] = intersections(profile.x,profile.y,x,y);
+
+%  sort intersections to create segments in order and continuous along profile
+[indices,isort]=sort(indices);
+j =j (isort);
+x0=x0(isort);
+y0=y0(isort);
+
+%process x0,y0 so they do not include profile.x or profile.y
+processed_indices=[];
+processed_x=[];
+processed_y=[];
+for i=1:numel(indices),
+	if(((indices(i)-floor(indices(i)))~=0) && ((ceil(indices(i))-indices(i))~=0))
+		processed_indices=[processed_indices;floor(indices(i))];
+		processed_x=[processed_x;x0(i)];
+		processed_y=[processed_y;y0(i)];
+	end
+end
+
+%now merge profile.x,profile.y with processed_x,processed_y, at locations processed_indices:
+newx=profile.x;
+newy=profile.y;
+
+count=1;
+for i=1:numel(profile.x),
+	pos=find(processed_indices==i);
+	if ~isempty(pos),
+		newx=[newx(1:count); processed_x(pos); newx(count+1:end)];
+		newy=[newy(1:count); processed_y(pos); newy(count+1:end)];
+		count=count+length(pos)+1;
+	end
+end
+
+%now, for each node, figure out which element it belongs to.
+node_in_element=NodeInElement(newx,newy,md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.vertexconnectivity);
+
+% eliminate nodes that don't fall in any element
+% (profile may start and/or end externally and/or cross holes in the model)
+
+ind=find(node_in_element(:,9)>0);
+newx=newx(ind,:);
+newy=newy(ind,:);
+node_in_element=node_in_element(ind,:);
+
+mesh_profile=[newx(1:end-1) newy(1:end-1) newx(2:end) newy(2:end) zeros(length(newy(2:end)),1)];
+
+%find which element each segment belongs to.
+for i=1:length(newx)-1,
+	common=intersect(node_in_element(i,1:node_in_element(i,end)), node_in_element(i+1,1:node_in_element(i+1,end)));
+	mesh_profile(i,end)=common(1);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/argusmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/argusmesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/argusmesh.m	(revision 13101)
@@ -0,0 +1,96 @@
+function md=argusmesh(md,infile)
+%ARGUSMESH - load an Argus mesh onto a model
+%
+%   Convert an Argus mesh contained in a file into
+%   fields needed for the mesh in a model md.
+%
+%   Usage:
+%      md=argusmesh(md,infile)
+%
+%   Example:
+%     md=argusmesh(md,'TriMesh.exp')
+
+%some argument check: 
+if nargin~=2 | nargout~=1,
+	help argustomodel;
+	error('argustomodel error message: bad usage');
+end
+
+%determine root of infile: strip extension
+[a,root,b,c]=fileparts(infile);
+
+%inform user we start the script: 
+disp(['   Translating argus file ''' infile ''' into matlab model object']);
+
+%open infile: 
+fileid=fopen(infile,'r');
+if fileid==-1,
+	error(['Could not open file ' infile  ' for reading']);
+end
+
+%Read first line of the argus mesh: node and element parameters
+[buffer,bytecount]=fscanf(fileid,'%i %i %i %i',[1 4]);
+if bytecount~=4, 
+	error(['Problem reading ' infile ' file at line #1']);
+end
+nel=buffer(1);
+nods=buffer(2);
+num_element_parameters=buffer(3);
+num_node_parameters=buffer(4);
+disp(['      argus model '''   root ''' contains ' num2str(nel) ' elements and ' num2str(nods) ' nodes.']);
+
+%initialize elements and nodes
+elements=zeros(nel,3);
+element_parameters=zeros(nel,num_element_parameters);
+x=zeros(nods,1);
+y=zeros(nods,1);
+z=zeros(nods,1);
+node_parameters=zeros(nods,num_node_parameters);
+
+%read nodes:
+format_string='%s %i %f %f ';
+for n=1:num_node_parameters,
+	format_string=[format_string ' %i '];
+end
+
+for n=1:nods,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_node_parameters+4]);
+	x(n)=buffer(3);
+	y(n)=buffer(4);
+	node_parameters(n,:)=buffer(5:length(buffer));
+end
+
+%read elements: 
+format_string='%s %i %i %i %i';
+for n=1:num_element_parameters,
+	format_string=[format_string ' %i '];
+end
+for n=1:nel,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_element_parameters+5]);
+	elements(n,:)=buffer(3:5);
+	element_parameters(n,:)=buffer(6:length(buffer));
+end
+
+%Create a name and a note for this model: 
+notes=['Model created by Argus from input file: ' infile ' and parameter file: ' root '.par on: ' date];
+name=root;
+
+%Finally, use model constructor to build a complete model: 
+md.mesh.elements=elements;
+md.mesh.x=x;
+md.mesh.y=y;
+md.z=z;
+md.mesh.numberofvertices=size(md.mesh.x,1);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.dimension=2;
+md=addnote(md,notes);
+
+%Add segments and nodes on boundary
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary(md.mesh.segments(:,1))=1;
+md.mesh.vertexonboundary(md.mesh.segments(:,2))=1;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/bamg.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/bamg.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/bamg.m	(revision 13101)
@@ -0,0 +1,483 @@
+function md=bamg(md,varargin)
+%BAMG - mesh generation
+%
+%   Available options (for more details see ISSM website http://issm.jpl.nasa.gov/):
+%
+%   - domain :            followed by an ARGUS file that prescribes the domain outline
+%   - hmin :              minimum edge length (default is 10^-100)
+%   - hmax :              maximum edge length (default is 10^100)
+%   - hVertices :         imposed edge length for each vertex (geometry or mesh)
+%   - hminVertices :      minimum edge length for each vertex (mesh)
+%   - hmaxVertices :      maximum edge length for each vertex (mesh)
+%
+%   - anisomax :          maximum ratio between the smallest and largest edges (default is 10^30)
+%   - coeff :             coefficient applied to the metric (2-> twice as many elements, default is 1)
+%   - cutoff :            scalar used to compute the metric when metric type 2 or 3 are applied
+%   - err :               error used to generate the metric from a field
+%   - errg :              geometric error (default is 0.1)
+%   - field :             field of the model that will be used to compute the metric
+%                         to apply several fields, use one column per field
+%   - gradation :         maximum ratio between two adjacent edges
+%   - Hessiantype :       0 -> use double P2 projection (default)
+%                         1 -> use Green formula
+%   - KeepVertices :      try to keep initial vertices when adaptation is done on an existing mesh (default 1)
+%   - MaxCornerAngle :    maximum angle of corners in degree (default is 10)
+%   - maxnbv :            maximum number of vertices used to allocate memory (default is 10^6)
+%   - maxsubdiv :         maximum subdivision of exisiting elements (default is 10)
+%   - metric :            matrix (numberofnodes x 3) used as a metric
+%   - Metrictype :        1 -> absolute error          c/(err coeff^2) * Abs(H)        (default)
+%                         2 -> relative error          c/(err coeff^2) * Abs(H)/max(s,cutoff*max(s))
+%                         3 -> rescaled absolute error c/(err coeff^2) * Abs(H)/(smax-smin)
+%   - nbjacoby :          correction used by Hessiantype=1 (default is 1)
+%   - nbsmooth :          number of metric smoothing procedure (default is 3)
+%   - omega :             relaxation parameter of the smoothing procedure (default is 1.8)
+%   - power :             power applied to the metric (default is 1)
+%   - splitcorners :      split triangles whuch have 3 vertices on the outline (default is 1)
+%   - geometricalmetric : take the geometry into account to generate the metric (default is 0)
+%   - verbose :           level of verbosity (default is 1)
+%
+%   - rifts :             followed by an ARGUS file that prescribes the rifts
+%   - toltip :            tolerance to move tip on an existing point of the domain outline
+%   - tracks :            followed by an ARGUS file that prescribes the tracks that the mesh will stick to
+%   - RequiredVertices :  mesh vertices that are required. [x,y,ref]; ref is optional
+%   - tol :               if the distance between 2 points of the domain outline is less than tol, they
+%                         will be merged
+%
+%   Examples:
+%      md=bamg(md,'domain','DomainOutline.exp','hmax',3000);
+%      md=bamg(md,'field',[md.inversion.vel_obs md.geometry.thickness],'hmax',20000,'hmin',1000);
+%      md=bamg(md,'metric',A,'hmin',1000,'hmax',20000,'gradation',3,'anisomax',1);
+
+%process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%initialize the structures required as input of Bamg
+bamg_options=struct();
+bamg_geometry=bamggeom;
+bamg_mesh=bamgmesh;
+
+% Bamg Geometry parameters {{{
+if exist(options,'domain'),
+
+	%Check that file exists
+	domainfile=getfieldvalue(options,'domain');
+	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found ']); end
+
+	%Build geometry 
+	domain=expread(domainfile);
+	count=0;
+	for i=1:length(domain),
+
+		%Check that the domain is closed
+		if (domain(i).x(1)~=domain(i).x(end) | domain(i).y(1)~=domain(i).y(end)),
+			error('bamg error message: all contours provided in ''domain'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		if i>1,
+			flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0);
+			if any(~flags),
+				error('bamg error message: All holes should be stricly inside the principal domain');
+			end
+		end
+
+		%Add all points to bamg_geometry
+		nods=domain(i).nods-1; %the domain are closed 1=end;
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [domain(i).x(1:nods) domain(i).y(1:nods) ones(nods,1)]];
+		bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1*ones(nods,1)]];
+		if i>1, bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 1]; end
+
+		%update counter
+		count=count+nods;
+	end
+
+	%take care of rifts
+	if exist(options,'rifts'),
+
+		%Check that file exists
+		riftfile=getfieldvalue(options,'rifts');
+		if ~exist(riftfile,'file')
+			error(['bamg error message: file ' riftfile ' not found ']);
+		end
+		rift=expread(riftfile);
+
+		for i=1:length(rift),
+
+			%detect wether all points of the rift are inside the domain
+			flags=ContourToNodes(rift(i).x,rift(i).y,domain(1),0);
+			if ~flags,
+				error('one Rift has all his points outside of the domain outline'),
+
+			elseif any(~flags),
+				%We LOTS of work to do
+				disp('Rift tip outside of or on the domain has been detected and is being processed...');
+
+				%check that only one point is outsie (for now)
+				if sum(~flags)~=1,
+					error('bamg error message: only one point outside of the domain is supported yet');
+				end
+
+				%Move tip outside to the first position
+				if flags(1)==0,
+					%OK, first point is outside (do nothing),
+				elseif (flags(end)==0),
+					rift(i).x=flipud(rift(i).x);
+					rift(i).y=flipud(rift(i).y);
+				else
+					error('bamg error message: only a rift tip can be outside of the domain');
+				end
+
+				%Get cordinate of intersection point
+				x1=rift(i).x(1); y1=rift(i).y(1);
+				x2=rift(i).x(2); y2=rift(i).y(2);
+				for j=1:length(domain(1).x)-1;
+					if SegIntersect([x1 y1; x2 y2],[domain(1).x(j) domain(1).y(j); domain(1).x(j+1) domain(1).y(j+1)]),
+
+						%Get position of the two nodes of the edge in domain
+						i1=j;
+						i2=mod(j+1,domain(1).nods);
+
+						%rift is crossing edge [i1 i2] of the domain
+						%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+						x3=domain(1).x(i1); y3=domain(1).y(i1);
+						x4=domain(1).x(i2); y4=domain(1).y(i2);
+						x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+						y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+						segdis= sqrt((x4-x3)^2+(y4-y3)^2);
+						tipdis=[sqrt((x-x3)^2+(y-y3)^2)  sqrt((x-x4)^2+(y-y4)^2)];
+
+						if (min(tipdis)/segdis) < getfieldvalue(options,'toltip',0),
+							disp('moving tip-domain intersection point');
+
+							%Get position of the closest point
+							if tipdis(1)>tipdis(2),
+								pos=i2;
+							else
+								pos=i1;
+							end
+
+							%This point is only in Vertices (number pos).
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								pos count+1  (1+i);...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+
+						else
+							%Add intersection point to Vertices
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; x y 1];
+							count=count+1;
+
+							%Decompose the crossing edge in 2 subedges
+							pos=find(bamg_geometry.Edges(:,1)==i1 & bamg_geometry.Edges(:,2)==i2);
+							if isempty(pos) error('bamg error message: a problem occured...'); end
+							bamg_geometry.Edges=[bamg_geometry.Edges(1:pos-1,:);...
+								bamg_geometry.Edges(pos,1) count                           bamg_geometry.Edges(pos,3);...
+								count                      bamg_geometry.Edges(pos,2)   bamg_geometry.Edges(pos,3);...
+								bamg_geometry.Edges(pos+1:end,:)];
+
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								count  count+1  2 ;...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+						end
+					end
+				end
+			else
+				nods=rift(i).nods-1;
+				bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(:) rift(i).y(:) ones(nods+1,1)]];
+				bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods+1])  (1+i)*ones(nods,1)]];
+				count=count+nods+1;
+			end
+		end
+	end
+
+	%Deal with tracks
+	if exist(options,'tracks'),
+
+		%read tracks
+		track=getfieldvalue(options,'tracks');
+		if all(ischar(track)),
+			A=expread(track); 
+			track=[A.x A.y];
+		else
+			track=double(track); %for some reason, it is of class "single"
+		end
+		if(size(track,2)==2), track=[track 3*ones(size(track,1),1)]; end
+
+		%only keep those inside
+		flags=ContourToNodes(track(:,1),track(:,2),domainfile,0);
+		track=track(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(track,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; track];
+		bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  3*ones(nods-1,1)]];
+
+		%update counter
+		count=count+nods;
+	end
+
+	%Deal with vertices that need to be kept by mesher
+	if exist(options,'RequiredVertices'),
+
+		%recover RequiredVertices
+		requiredvertices=double(getfieldvalue(options,'RequiredVertices')); %for some reason, it is of class "single"
+		if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4*ones(size(requiredvertices,1),1)]; end
+	
+		%only keep those inside
+		flags=ContourToNodes(requiredvertices(:,1),requiredvertices(:,2),domain(1),0);
+		requiredvertices=requiredvertices(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(requiredvertices,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; requiredvertices];
+
+		%update counter
+		count=count+nods;
+
+	end
+
+	%process geom
+	%bamg_geometry=processgeometry(bamg_geometry,getfieldvalue(options,'tol',NaN),domain(1));
+
+elseif isstruct(md.private.bamg) & isfield(md.private.bamg,'geometry'),
+	bamg_geometry=bamggeom(md.private.bamg.geometry); 
+else
+	%do nothing...
+end
+%}}}
+% Bamg Mesh parameters {{{
+if (~exist(options,'domain') & md.mesh.numberofvertices~=0 & md.mesh.dimension==2),
+
+	if isstruct(md.private.bamg) & isfield(md.private.bamg,'mesh'),
+		bamg_mesh=bamgmesh(md.private.bamg.mesh);
+	else
+		bamg_mesh.Vertices=[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)];
+		bamg_mesh.Triangles=[md.mesh.elements ones(md.mesh.numberofelements,1)];
+	end
+
+	if isstruct(md.rifts.riftstruct)
+		error('bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg');
+	end
+end
+%}}}
+% Bamg Options {{{
+bamg_options.Crack=getfieldvalue(options,'Crack',0);
+bamg_options.anisomax=getfieldvalue(options,'anisomax',10^30);
+bamg_options.coeff=getfieldvalue(options,'coeff',1);
+bamg_options.cutoff=getfieldvalue(options,'cutoff',10^-5);
+bamg_options.err=getfieldvalue(options,'err',0.01);
+bamg_options.errg=getfieldvalue(options,'errg',0.1);
+bamg_options.field=getfieldvalue(options,'field',[]);
+bamg_options.gradation=getfieldvalue(options,'gradation',1.5);
+bamg_options.Hessiantype=getfieldvalue(options,'Hessiantype',0);
+bamg_options.hmin=getfieldvalue(options,'hmin',10^-100);
+bamg_options.hmax=getfieldvalue(options,'hmax',10^100);
+bamg_options.hminVertices=getfieldvalue(options,'hminVertices',[]);
+bamg_options.hmaxVertices=getfieldvalue(options,'hmaxVertices',[]);
+bamg_options.hVertices=getfieldvalue(options,'hVertices',[]);
+bamg_options.KeepVertices=getfieldvalue(options,'KeepVertices',1);
+bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10);
+bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
+bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10);
+bamg_options.metric=getfieldvalue(options,'metric',[]);
+bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
+bamg_options.nbjacobi=getfieldvalue(options,'nbjacobi',1);
+bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
+bamg_options.omega=getfieldvalue(options,'omega',1.8);
+bamg_options.power=getfieldvalue(options,'power',1);
+bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
+bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
+bamg_options.verbose=getfieldvalue(options,'verbose',1);
+%}}}
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgMesher(bamg_mesh,bamg_geometry,bamg_options);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.elementconnectivity=md.private.bamg.mesh.ElementConnectivity;
+md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+%Check for orphan
+reshape(md.mesh.elements,3*md.mesh.numberofelements,1);
+(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))));
+if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
+	error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
+end
+end 
+
+function geom=processgeometry(geom,tol,outline); % {{{
+
+%Deal with edges
+disp('Checking Edge crossing...');
+i=0;
+while (i<size(geom.Edges,1)),
+
+	%edge counter
+	i=i+1;
+
+	%Get coordinates
+	x1=geom.Vertices(geom.Edges(i,1),1);
+	y1=geom.Vertices(geom.Edges(i,1),2);
+	x2=geom.Vertices(geom.Edges(i,2),1);
+	y2=geom.Vertices(geom.Edges(i,2),2);
+	color1=geom.Edges(i,3);
+
+	j=i; %test edges located AFTER i only
+	while (j<size(geom.Edges,1)),
+
+		%edge counter
+		j=j+1;
+
+		%Skip if the two edges already have a vertex in common
+		if any(ismember(geom.Edges(i,1:2),geom.Edges(j,1:2))),
+			continue
+		end
+
+		%Get coordinates
+		x3=geom.Vertices(geom.Edges(j,1),1);
+		y3=geom.Vertices(geom.Edges(j,1),2);
+		x4=geom.Vertices(geom.Edges(j,2),1);
+		y4=geom.Vertices(geom.Edges(j,2),2);
+		color2=geom.Edges(j,3);
+
+		%Check if the two edges are crossing one another
+		if SegIntersect([x1 y1; x2 y2],[x3 y3; x4 y4]),
+
+			%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+			x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+			y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+			%Add vertex to the list of vertices
+			geom.Vertices(end+1,:)=[x y min(color1,color2)];
+			id=size(geom.Vertices,1);
+
+			%Update edges i and j
+			edgei=geom.Edges(i,:);
+			edgej=geom.Edges(j,:);
+			geom.Edges(i,:)    =[edgei(1) id       edgei(3)];
+			geom.Edges(end+1,:)=[id       edgei(2) edgei(3)];
+			geom.Edges(j,:)    =[edgej(1) id       edgej(3)];
+			geom.Edges(end+1,:)=[id       edgej(2) edgej(3)];
+
+			%update current edge second tip
+			x2=x; y2=y;
+		end
+	end
+
+end
+
+%Check point outside
+disp('Checking for points outside the domain...');
+i=0;
+num=0;
+while (i<size(geom.Vertices,1)),
+
+	%vertex counter
+	i=i+1;
+
+	%Get coordinates
+	x=geom.Vertices(i,1);
+	y=geom.Vertices(i,2);
+	color=geom.Vertices(i,3);
+
+	%Check that the point is inside the domain
+	if (color~=1 & ~ContourToNodes(x,y,outline(1),1)),
+
+		%Remove points from list of Vertices
+		num=num+1;
+		geom.Vertices(i,:)=[];
+
+		%update edges
+		[posedges dummy]=find(geom.Edges==i);
+		geom.Edges(posedges,:)=[];
+		posedges=find(geom.Edges>i);
+		geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+		%update counter
+		i=i-1;
+	end
+end
+if num,
+	disp(['WARNING: ' num2str(num) ' points outside the domain outline have been removed']);
+end
+
+%Check point spacing
+if ~isnan(tol),
+	disp('Checking point spacing...');
+	i=0;
+	while (i<size(geom.Vertices,1)),
+
+		%vertex counter
+		i=i+1;
+
+		%Get coordinates
+		x1=geom.Vertices(i,1);
+		y1=geom.Vertices(i,2);
+
+		j=i; %test edges located AFTER i only
+		while (j<size(geom.Vertices,1)),
+
+			%vertex counter
+			j=j+1;
+
+			%Get coordinates
+			x2=geom.Vertices(j,1);
+			y2=geom.Vertices(j,2);
+
+			%Check whether the two vertices are too close
+			if ((x2-x1)^2+(y2-y1)^2<tol^2)
+
+				%Remove points from list of Vertices
+				geom.Vertices(j,:)=[];
+
+				%update edges
+				posedges=find(ismember(geom.Edges,j));
+				geom.Edges(posedges)=i;
+				posedges=find(geom.Edges>j);
+				geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+				%update counter
+				j=j-1;
+
+			end
+		end
+	end
+end
+%remove empty edges
+geom.Edges(find(geom.Edges(:,1)==geom.Edges(:,2)),:)=[];
+end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/findsegments.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/findsegments.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/findsegments.m	(revision 13101)
@@ -0,0 +1,92 @@
+function segments=findsegments(md,varargin)
+%FINDSEGMENTS - build segments model field
+%
+%   Optional inputs:
+%      'mesh.elementconnectivity'
+%
+%   Usage:
+%      segments=findsegments(md,varargin);
+
+%get options
+options=pairoptions(varargin{:});
+
+%Get connectivity
+mesh.elementconnectivity=getfieldvalue(options,'mesh.elementconnectivity',md.mesh.elementconnectivity);
+
+%Now, build the connectivity tables for this mesh if not correclty done
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	if exist(options,'mesh.elementconnectivity'),
+		error(' ''mesh.elementconnectivity'' option does not have thge right size.');
+	else
+		mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+	end
+end
+
+%Recreate the segments
+elementonboundary=double(mesh.elementconnectivity(:,3)==0);
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+%loop over the segments
+for i=1:num_segments,
+
+	%get current element on boundary
+	el1=pos(i);
+
+	%get elements connected to el1
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+
+	%el1 is connected to 2 other elements
+	if length(els2)>1,
+
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the common vertices to the two elements connected to el1 (1 or 2)
+		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
+
+		%get the vertices on the boundary and build segment
+		nods1(find(ismember(nods1,flag)))=[];
+		segments(count,:)=[nods1 el1];
+
+		%swap segment nodes if necessary
+		ord1=find(nods1(1)==md.mesh.elements(el1,:));
+		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+
+	%el1 is connected to only one element
+	else
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the vertex  the el1 to not share with els2
+		flag=setdiff(nods1,md.mesh.elements(els2,:));
+
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+
+				segments(count,:)=[nods el1];
+
+				%swap segment nodes if necessary
+				ord1=find(nods(1)==md.mesh.elements(el1,:));
+				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/intersections.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/intersections.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/intersections.m	(revision 13101)
@@ -0,0 +1,279 @@
+function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
+%INTERSECTIONS Intersections of curves.
+%   Computes the (x,y) locations where two curves intersect.  The curves
+%   can be broken with NaNs or have vertical segments.
+%
+% Example:
+%   [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% where X1 and Y1 are equal-length vectors of at least two points and
+% represent curve 1.  Similarly, X2 and Y2 represent curve 2.
+% X0 and Y0 are column vectors containing the points at which the two
+% curves intersect.
+%
+% ROBUST (optional) set to 1 or true means to use a slight variation of the
+% algorithm that might return duplicates of some intersection points, and
+% then remove those duplicates.  The default is true, but since the
+% algorithm is slightly slower you can set it to false if you know that
+% your curves don't intersect at any segment boundaries.  Also, the robust
+% version properly handles parallel and overlapping segments.
+%
+% The algorithm can return two additional vectors that indicate which
+% segment pairs contain intersections and where they are:
+%
+%   [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
+% (how far along this segment the intersection is).  For example, if I(k) =
+% 45.25 then the intersection lies a quarter of the way between the line
+% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)).  Similarly for
+% the vector J and the segments in (X2,Y2).
+%
+% You can also get intersections of a curve with itself.  Simply pass in
+% only one curve, i.e.,
+%
+%   [X0,Y0] = intersections(X1,Y1,ROBUST);
+%
+% where, as before, ROBUST is optional.
+
+% Version: 1.10, 25 February 2008
+% Author:  Douglas M. Schwarz
+% Email:   dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
+% Real_email = regexprep(Email,{'=','*'},{'@','.'})
+
+
+% Theory of operation:
+%
+% Given two line segments, L1 and L2,
+%
+%   L1 endpoints:  (x1(1),y1(1)) and (x1(2),y1(2))
+%   L2 endpoints:  (x2(1),y2(1)) and (x2(2),y2(2))
+%
+% we can write four equations with four unknowns and then solve them.  The
+% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
+% L1 and L2, t1 is the distance from the starting point of L1 to the
+% intersection relative to the length of L1 and t2 is the distance from the
+% starting point of L2 to the intersection relative to the length of L2.
+%
+% So, the four equations are
+%
+%    (x1(2) - x1(1))*t1 = x0 - x1(1)
+%    (x2(2) - x2(1))*t2 = x0 - x2(1)
+%    (y1(2) - y1(1))*t1 = y0 - y1(1)
+%    (y2(2) - y2(1))*t2 = y0 - y2(1)
+%
+% Rearranging and writing in matrix form,
+%
+%  [x1(2)-x1(1)       0       -1   0;      [t1;      [-x1(1);
+%        0       x2(2)-x2(1)  -1   0;   *   t2;   =   -x2(1);
+%   y1(2)-y1(1)       0        0  -1;       x0;       -y1(1);
+%        0       y2(2)-y2(1)   0  -1]       y0]       -y2(1)]
+%
+% Let's call that A*T = B.  We can solve for T with T = A\B.
+%
+% Once we have our solution we just have to look at t1 and t2 to determine
+% whether L1 and L2 intersect.  If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
+% line segments cross and we can include (x0,y0) in the output.
+%
+% In principle, we have to perform this computation on every pair of line
+% segments in the input data.  This can be quite a large number of pairs so
+% we will reduce it by doing a simple preliminary check to eliminate line
+% segment pairs that could not possibly cross.  The check is to look at the
+% smallest enclosing rectangles (with sides parallel to the axes) for each
+% line segment pair and see if they overlap.  If they do then we have to
+% compute t1 and t2 (via the A\B computation) to see if the line segments
+% cross, but if they don't then the line segments cannot cross.  In a
+% typical application, this technique will eliminate most of the potential
+% line segment pairs.
+
+
+% Input checks.
+error(nargchk(2,5,nargin))
+
+% Adjustments when fewer than five arguments are supplied.
+switch nargin
+	case 2
+		robust = true;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 3
+		robust = x2;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 4
+		robust = true;
+		self_intersect = false;
+	case 5
+		self_intersect = false;
+end
+
+% x1 and y1 must be vectors with same number of points (at least 2).
+if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
+		length(x1) ~= length(y1)
+	error('X1 and Y1 must be equal-length vectors of at least 2 points.')
+end
+% x2 and y2 must be vectors with same number of points (at least 2).
+if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
+		length(x2) ~= length(y2)
+	error('X2 and Y2 must be equal-length vectors of at least 2 points.')
+end
+
+
+% Force all inputs to be column vectors.
+x1 = x1(:);
+y1 = y1(:);
+x2 = x2(:);
+y2 = y2(:);
+
+% Compute number of line segments in each curve and some differences we'll
+% need later.
+n1 = length(x1) - 1;
+n2 = length(x2) - 1;
+xy1 = [x1 y1];
+xy2 = [x2 y2];
+dxy1 = diff(xy1);
+dxy2 = diff(xy2);
+
+% Determine the combinations of i and j where the rectangle enclosing the
+% i'th line segment of curve 1 overlaps with the rectangle enclosing the
+% j'th line segment of curve 2.
+[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...
+	repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...
+	repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...
+	repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...
+	repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...
+	repmat(min(y2(1:end-1),y2(2:end)).',n1,1));
+
+% For one segment in x1,y1, i and j are returned as row vectors.  They
+% need to be column vectors, or iout and jout below will err out.
+% (jes, 6/11/10)
+
+if (size(i,1) == 1)
+    i=i';
+end
+if (size(j,1) == 1)
+    j=j';
+end
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+% At the same time we can remove redundant combinations of i and j in the
+% case of finding intersections of a line with itself.
+if self_intersect
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
+else
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+end
+i(remove) = [];
+j(remove) = [];
+
+% Initialize matrices.  We'll put the T's and B's in matrices and use them
+% one column at a time.  AA is a 3-D extension of A where we'll use one
+% plane at a time.
+n = length(i);
+T = zeros(4,n);
+AA = zeros(4,4,n);
+AA([1 2],3,:) = -1;
+AA([3 4],4,:) = -1;
+AA([1 3],1,:) = dxy1(i,:).';
+AA([2 4],2,:) = dxy2(j,:).';
+B = -[x1(i) x2(j) y1(i) y2(j)].';
+
+% Loop through possibilities.  Trap singularity warning and then use
+% lastwarn to see if that plane of AA is near singular.  Process any such
+% segment pairs to determine if they are colinear (overlap) or merely
+% parallel.  That test consists of checking to see if one of the endpoints
+% of the curve 2 segment lies on the curve 1 segment.  This is done by
+% checking the cross product
+%
+%   (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
+%
+% If this is close to zero then the segments overlap.
+
+% If the robust option is false then we assume no two segment pairs are
+% parallel and just go ahead and do the computation.  If A is ever singular
+% a warning will appear.  This is faster and obviously you should use it
+% only when you know you will never have overlapping or parallel segment
+% pairs.
+
+if robust
+	overlap = false(1,n);
+	warning_state = warning('off','MATLAB:singularMatrix');
+	% Use try-catch to guarantee original warning state is restored.
+	try
+		lastwarn('')
+		for k = 1:n
+			T(:,k) = AA(:,:,k)\B(:,k);
+			[unused,last_warn] = lastwarn;
+			lastwarn('')
+			if strcmp(last_warn,'MATLAB:singularMatrix')
+				% Force in_range(k) to be false.
+				T(1,k) = NaN;
+				% Determine if these segments overlap or are just parallel.
+				overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
+			end
+		end
+		warning(warning_state)
+	catch
+		warning(warning_state)
+		rethrow(lasterror)
+	end
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1;
+	% For overlapping segment pairs the algorithm will return an
+	% intersection point that is at the center of the overlapping region.
+	if any(overlap)
+		ia = i(overlap);
+		ja = j(overlap);
+		% set x0 and y0 to middle of overlapping region.
+		T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
+			min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
+		T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
+			min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
+		selected = in_range | overlap;
+	else
+		selected = in_range;
+	end
+	xy0 = T(3:4,selected).';
+	
+	% Remove duplicate intersection points.
+	[xy0,index] = unique(xy0,'rows');
+	x0 = xy0(:,1);
+	y0 = xy0(:,2);
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		sel_index = find(selected);
+		sel = sel_index(index);
+		iout = i(sel) + T(1,sel).';
+		jout = j(sel) + T(2,sel).';
+	end
+else % non-robust option
+	for k = 1:n
+		[L,U] = lu(AA(:,:,k));
+		T(:,k) = U\(L\B(:,k));
+	end
+	
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1;
+	x0 = T(3,in_range).';
+	y0 = T(4,in_range).';
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		iout = i(in_range) + T(1,in_range).';
+		jout = j(in_range) + T(2,in_range).';
+	end
+end
+
+% Plot the results (useful for debugging).
+% plot(x1,y1,x2,y2,x0,y0,'ok');
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/meshconvert.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/meshconvert.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/meshconvert.m	(revision 13101)
@@ -0,0 +1,48 @@
+function md=meshconvert(md,varargin)
+%CONVERTMESH - convert mesh to bamg mesh
+%
+%   Usage:
+%      md=meshconvert(md);
+%      md=meshconvert(md,index,x,y);
+
+if nargin~=1 & nargin~=4,
+	help meshconvert
+	error('meshconvert error message: bad usage');
+end
+
+if nargin==1,
+	x=md.mesh.x;
+	y=md.mesh.y;
+	index=md.mesh.elements;
+else
+	x=varargin{1};
+	y=varargin{2};
+	index=varargin{3};
+end
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgConvertMesh(index,x,y);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/mesh_refine_tri4.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/mesh_refine_tri4.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/mesh_refine_tri4.m	(revision 13101)
@@ -0,0 +1,146 @@
+function [ FV ] = mesh_refine_tri4(FV)
+
+% mesh_refine_tri4 - creates 4 triangle from each triangle of a mesh
+%
+% [ FV ] = mesh_refine_tri4( FV )
+%
+% FV.vertices   - mesh vertices (Nx3 matrix)
+% FV.faces      - faces with indices into 3 rows
+%                 of FV.vertices (Mx3 matrix)
+% 
+% For each face, 3 new vertices are created at the 
+% triangle edge midpoints.  Each face is divided into 4
+% faces and returned in FV.
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+% 
+% It is assumed that the vertices are listed in clockwise order in
+% FV.faces (A,B,C above), as viewed from the outside in a RHS coordinate
+% system.
+% 
+% See also: mesh_refine, sphere_tri, sphere_project
+% 
+
+
+% ---this method is not implemented, but the idea here remains...
+% This can be done until some minimal distance (D) of the mean 
+% distance between vertices of all triangles is achieved.  If
+% no D argument is given, the function refines the mesh once.
+% Alternatively, it could be done until some minimum mean 
+% area of faces is achieved.  As is, it just refines once.
+
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:35 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  05/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+tic;
+fprintf('...refining mesh (tri4)...')
+
+% NOTE
+% The centroid is located one third of the way from each vertex to 
+% the midpoint of the opposite side. Each median divides the triangle 
+% into two equal areas; all the medians together divide it into six 
+% equal parts, and the lines from the median point to the vertices 
+% divide the whole into three equivalent triangles.
+
+% Each input triangle with vertices labelled [A,B,C] as shown
+% below will be turned into four new triangles:
+%
+% Make new midpoints
+% a = (A+B)/2
+% b = (B+C)/2
+% c = (C+A)/2
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+%
+
+% Initialise a new vertices and faces matrix
+Nvert = size(FV.vertices,1);
+Nface = size(FV.faces,1);
+V2 = zeros(Nface*3,3);
+F2 = zeros(Nface*4,3);
+
+for f = 1:Nface,
+    
+    % Get the triangle vertex indices
+    NA = FV.faces(f,1);
+    NB = FV.faces(f,2);
+    NC = FV.faces(f,3);
+    
+    % Get the triangle vertex coordinates
+    A = FV.vertices(NA,:);
+    B = FV.vertices(NB,:);
+    C = FV.vertices(NC,:);
+    
+    % Now find the midpoints between vertices
+    a = (A + B) ./ 2;
+    b = (B + C) ./ 2;
+    c = (C + A) ./ 2;
+    
+    % Find the length of each median
+    %A2blen = sqrt ( sum( (A - b).^2, 2 ) );
+    %B2clen = sqrt ( sum( (B - c).^2, 2 ) );
+    %C2alen = sqrt ( sum( (C - a).^2, 2 ) );
+    
+    % Store the midpoint vertices, while
+    % checking if midpoint vertex already exists
+    [FV, Na] = mesh_find_vertex(FV,a);
+    [FV, Nb] = mesh_find_vertex(FV,b);
+    [FV, Nc] = mesh_find_vertex(FV,c);
+    
+    % Create new faces with orig vertices plus midpoints
+    F2(f*4-3,:) = [ NA, Na, Nc ];
+    F2(f*4-2,:) = [ Na, NB, Nb ];
+    F2(f*4-1,:) = [ Nc, Nb, NC ];
+    F2(f*4-0,:) = [ Na, Nb, Nc ];
+    
+end
+
+% Replace the faces matrix
+FV.faces = F2;
+
+t=toc; fprintf('done (%5.2f sec)\n',t);
+
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [FV, N] = mesh_find_vertex(FV,vertex)
+
+    Vn = size(FV.vertices,1);
+    Va = repmat(vertex,Vn,1);
+    Vexist = find( FV.vertices(:,1) == Va(:,1) & ...
+                   FV.vertices(:,2) == Va(:,2) & ...
+                   FV.vertices(:,3) == Va(:,3) );
+    if Vexist,
+        if size(Vexist) == [1,1],
+            N = Vexist;
+        else,
+            msg = sprintf('replicated vertices');
+            error(msg);
+        end
+    else
+        FV.vertices(end+1,:) = vertex;
+        N = size(FV.vertices,1);
+    end
+
+return
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmesher.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmesher.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmesher.m	(revision 13101)
@@ -0,0 +1,35 @@
+function md=planetmesher(md,varargin)
+%PLANETMESHER - create planet mesh using several packages
+%
+%   This routine creates a planet mesh using several packages: a custom made 
+%   ISSM mesher (called planetmixedmesh.m, method 'mixed') and the planettrimesh
+%   (method 'tria')
+%   where md is a @planet object, varargin is a list of options
+%
+% Usage: md=planetmesher(md,'method','mixed','radius',6378000,'angleresol',1);
+%        md=planetmesher(md,'method','tria','shape','iso','radius',6378000,'refinement',5);
+%
+%
+
+	%recover options
+	options=pairoptions(varargin{:});
+
+	method=getfieldvalue(options,'method','mixed');
+
+	if strcmpi(method,'mixed'),
+		%recover radius and angleresol: 
+		radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+		angleresol=getfieldvalue(options,'angleresol',10); %10 degree resolution
+
+		%call mixed mesh 
+		md=planetmixedmesh(md,radius,angleresol);
+	else
+		%recover radius, shape and level of refinmenet
+		radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+		refinement=getfieldvalue(options,'refinement',5); %refine 5 times
+		shape=getfieldvalue(options,'shape','ico'); 
+
+		%call triangular mesh
+		md=planettrimesh(md,shape,radius,refinement);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmixedmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmixedmesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planetmixedmesh.m	(revision 13101)
@@ -0,0 +1,99 @@
+function md=planetmixedmesh(md,radius,angleresol)
+%PLANETMIXEDMESH: build 2d shell mesh
+%
+% Usage: md=planetmixedshell(md,radius,angleresol)
+%
+
+conv=pi/180;
+
+r=radius;
+theta=(0:angleresol:360)';
+theta=theta*conv;
+phi=(0:angleresol:180)';
+phi=phi(2:end-1)*conv;
+
+nphi=length(phi);
+nthetha=length(theta);
+
+x=zeros(nphi*nthetha,1);
+y=zeros(nphi*nthetha,1);
+z=zeros(nphi*nthetha,1);
+
+for i=1:nphi,
+	phii=phi(i);
+	x((i-1)*nthetha+1:i*nthetha)=r.*cos(theta).*sin(phii);
+	y((i-1)*nthetha+1:i*nthetha)=r.*sin(theta).*sin(phii);
+	z((i-1)*nthetha+1:i*nthetha)=r.*cos(phii);
+end
+
+quads=zeros((nthetha-1)*(nphi-1),4);
+
+%build elements
+for i=1:nphi-1,
+	for j=1:nthetha-1,
+		count=(i-1)*(nthetha-1)+j;
+	
+		A=(i-1)*nthetha+j;
+		B=(i-1)*nthetha+j+1;
+		C=(i)*nthetha+j+1;
+		D=(i)*nthetha+j;
+		
+		quads(count,:)=[A B C D];
+	end
+end
+
+%now, add polar elements:
+%first north: phi = 0;
+x=[r.*cos(0).*sin(0);x];
+y=[r.*sin(0).*sin(0);y];
+z=[r.*cos(0);z];
+
+%add 1 to quads: 
+quads=quads+1;
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+for i=1:nthetha-1,
+	A=1;
+	B=i+1;
+	C=i+2;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[trias;quads];
+
+
+% now add south pole: 
+phii=180*conv;
+x=[x;r.*cos(phii).*sin(phii)];
+y=[y;r.*sin(phii).*sin(phii)];
+z=[z;r.*cos(phii)];
+nods=length(x);
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+start=nods-nthetha;
+for i=1:nthetha-1,
+	A=start+i-1;
+	B=start+i;
+	C=nods;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[quads;trias];
+
+
+md.mesh.elements=quads;
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.z=z;
+md.mesh.r=sqrt(x.^2+y.^2+z.^2);
+md.mesh.theta=acos(z./md.mesh.r);
+md.mesh.phi=atan2(y,x);
+
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planettrimesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planettrimesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/planettrimesh.m	(revision 13101)
@@ -0,0 +1,20 @@
+function md=planettrimesh(md,shape,radius,refinement)
+%PLANETTRIMESH: build 2d shell mesh
+%
+% Usage: md=planettrimesh(md,shape,radius,refinement)
+%
+
+results = sphere_tri(shape,refinement,radius);
+md.mesh.x=results.vertices(:,1);
+md.mesh.y=results.vertices(:,2);
+md.mesh.z=results.vertices(:,3);
+md.mesh.elements=results.faces;
+
+md.mesh.r=sqrt(md.mesh.x.^2+md.mesh.y.^2+md.mesh.z.^2);
+md.mesh.theta=acos(md.mesh.z./md.mesh.r);
+md.mesh.phi=atan2(md.mesh.y,md.mesh.x);
+
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_project.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_project.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_project.m	(revision 13101)
@@ -0,0 +1,66 @@
+function V = sphere_project(v,r,c)
+
+% sphere_project - project point X,Y,Z to the surface of sphere radius r
+% 
+% V = sphere_project(v,r,c)
+% 
+% Cartesian inputs:
+% v is the vertex matrix, Nx3 (XYZ)
+% r is the sphere radius, 1x1 (default 1)
+% c is the sphere centroid, 1x3 (default 0,0,0)
+%
+% XYZ are converted to spherical coordinates and their radius is
+% adjusted according to r, from c toward XYZ (defined with theta,phi)
+% 
+% V is returned as Cartesian 3D coordinates
+% 
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:36 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  06/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~exist('v','var'),
+    msg = sprintf('SPHERE_PROJECT: No input vertices (X,Y,Z)\n');
+    error(msg);
+end
+
+X = v(:,1);
+Y = v(:,2);
+Z = v(:,3);
+
+if ~exist('c','var'),
+    xo = 0;
+    yo = 0;
+    zo = 0;
+else
+    xo = c(1);
+    yo = c(2);
+    zo = c(3);
+end
+
+if ~exist('r','var'), r = 1; end
+
+% alternate method is to use unit vector of V
+% [ n = 'magnitude(V)'; unitV = V ./ n; ]
+% to change the radius, multiply the unitV
+% by the radius required.  This avoids the
+% use of arctan functions, which have branches.
+
+
+% Convert Cartesian X,Y,Z to spherical (radians)
+theta = atan2( (Y-yo), (X-xo) );
+phi   = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );
+% do not calc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);
+
+%   Recalculate X,Y,Z for constant r, given theta & phi.
+R = ones(size(phi)) * r;
+x = R .* sin(phi) .* cos(theta);
+y = R .* sin(phi) .* sin(theta);
+z = R .* cos(phi);
+
+V = [x y z];
+
+return
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_tri.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_tri.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/planet/sphere_tri.m	(revision 13101)
@@ -0,0 +1,204 @@
+function [FV] = sphere_tri(shape,maxlevel,r,winding)
+
+% sphere_tri - generate a triangle mesh approximating a sphere
+% 
+% Usage: FV = sphere_tri(shape,Nrecurse,r,winding)
+% 
+%   shape is a string, either of the following:
+%   'ico'   starts with icosahedron (most even, default)
+%   'oct'   starts with octahedron
+%   'tetra' starts with tetrahedron (least even)
+%
+%   Nrecurse is int >= 0, setting the recursions (default 0)
+%
+%   r is the radius of the sphere (default 1)
+%
+%   winding is 0 for clockwise, 1 for counterclockwise (default 0).  The
+%   matlab patch command gives outward surface normals for clockwise
+%   order of vertices in the faces (viewed from outside the surface).
+%
+%   FV has fields FV.vertices and FV.faces.  The vertices 
+%   are listed in clockwise order in FV.faces, as viewed 
+%   from the outside in a RHS coordinate system.
+% 
+% The function uses recursive subdivision.  The first
+% approximation is an platonic solid, either an  icosahedron,
+% octahedron or a tetrahedron.  Each level of refinement 
+% subdivides each triangle face by a factor of 4 (see also 
+% mesh_refine).  At each refinement, the vertices are 
+% projected to the sphere surface (see sphere_project).
+% 
+% A recursion level of 3 or 4 is a good sphere surface, if
+% gouraud shading is used for rendering.
+% 
+% The returned struct can be used in the patch command, eg:
+% 
+% % create and plot, vertices: [2562x3] and faces: [5120x3]
+% FV = sphere_tri('ico',4,1);
+% lighting phong; shading interp; figure;
+% patch('vertices',FV.vertices,'faces',FV.faces,...
+%       'facecolor',[1 0 0],'edgecolor',[.2 .2 .6]);
+% axis off; camlight infinite; camproj('perspective');
+% 
+% See also: mesh_refine, sphere_project
+%
+
+
+
+% $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% Jon Leech (leech @ cs.unc.edu) 3/24/89
+% icosahedral code added by Jim Buddenhagen (jb1556@daditz.sbc.com) 5/93
+% 06/2002, adapted from c to matlab by Darren.Weber_at_radiology.ucsf.edu
+% 05/2004, reorder of the faces for the 'ico' surface so they are indeed
+% clockwise!  Now the surface normals are directed outward.  Also reset the
+% default recursions to zero, so we can get out just the platonic solids.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+eegversion = '$Revision: 1.2 $';
+fprintf('SPHERE_TRI [v %s]\n',eegversion(11:15)); tic
+
+if ~exist('shape','var') || isempty(shape),
+    shape = 'ico';
+end
+fprintf('...creating sphere tesselation based on %s\n',shape);
+
+% default maximum subdivision level
+if ~exist('maxlevel','var') || isempty(maxlevel) || maxlevel < 0,
+    maxlevel = 0;
+end
+
+% default radius
+if ~exist('r','var') || isempty(r),
+    r = 1;
+end
+
+if ~exist('winding','var') || isempty(winding),
+    winding = 0;
+end
+
+
+% -----------------
+% define the starting shapes
+
+shape = lower(shape);
+
+switch shape,
+case 'tetra',
+    
+    % Vertices of a tetrahedron
+    sqrt_3 = 0.5773502692;
+    
+    tetra.v = [  sqrt_3,  sqrt_3,  sqrt_3 ;   % +X, +Y, +Z  - PPP
+                -sqrt_3, -sqrt_3,  sqrt_3 ;   % -X, -Y, +Z  - MMP
+                -sqrt_3,  sqrt_3, -sqrt_3 ;   % -X, +Y, -Z  - MPM
+                 sqrt_3, -sqrt_3, -sqrt_3 ];  % +X, -Y, -Z  - PMM
+	
+    % Structure describing a tetrahedron
+    tetra.f = [ 1, 2, 3;
+                1, 4, 2;
+                3, 2, 4;
+                4, 1, 3 ];
+    
+    FV.vertices = tetra.v;
+    FV.faces    = tetra.f;
+    
+case 'oct',
+    
+    % Six equidistant points lying on the unit sphere
+    oct.v = [  1,  0,  0 ;  %  X
+              -1,  0,  0 ; 	% -X
+               0,  1,  0 ;  %  Y
+               0, -1,  0 ; 	% -Y
+               0,  0,  1 ; 	%  Z
+               0,  0, -1 ];	% -Z
+	
+    % Join vertices to create a unit octahedron
+    oct.f = [ 1 5 3 ;    %  X  Z  Y  -  First the top half
+              3 5 2 ;    %  Y  Z -X
+              2 5 4 ;    % -X  Z -Y
+              4 5 1 ;    % -Y  Z  X
+              1 3 6 ;    %  X  Y -Z  -  Now the bottom half
+              3 2 6 ;    %  Y  Z -Z
+              2 4 6 ;    % -X  Z -Z
+              4 1 6 ];   % -Y  Z -Z
+    
+    FV.vertices = oct.v;
+    FV.faces    = oct.f;
+    
+case 'ico',
+    
+    % Twelve vertices of icosahedron on unit sphere
+    tau = 0.8506508084; % t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2)
+    one = 0.5257311121; % one=1/sqrt(1+t^2) , unit sphere
+    
+    ico.v( 1,:) = [  tau,  one,    0 ]; % ZA
+    ico.v( 2,:) = [ -tau,  one,    0 ]; % ZB
+    ico.v( 3,:) = [ -tau, -one,    0 ]; % ZC
+    ico.v( 4,:) = [  tau, -one,    0 ]; % ZD
+    ico.v( 5,:) = [  one,   0 ,  tau ]; % YA
+    ico.v( 6,:) = [  one,   0 , -tau ]; % YB
+    ico.v( 7,:) = [ -one,   0 , -tau ]; % YC
+    ico.v( 8,:) = [ -one,   0 ,  tau ]; % YD
+    ico.v( 9,:) = [   0 ,  tau,  one ]; % XA
+    ico.v(10,:) = [   0 , -tau,  one ]; % XB
+    ico.v(11,:) = [   0 , -tau, -one ]; % XC
+    ico.v(12,:) = [   0 ,  tau, -one ]; % XD
+    
+    % Structure for unit icosahedron
+    ico.f = [  5,  8,  9 ;
+               5, 10,  8 ;
+               6, 12,  7 ;
+               6,  7, 11 ;
+               1,  4,  5 ;
+               1,  6,  4 ;
+               3,  2,  8 ;
+               3,  7,  2 ;
+               9, 12,  1 ;
+               9,  2, 12 ;
+              10,  4, 11 ;
+              10, 11,  3 ;
+               9,  1,  5 ;
+              12,  6,  1 ;
+               5,  4, 10 ;
+               6, 11,  4 ;
+               8,  2,  9 ;
+               7, 12,  2 ;
+               8, 10,  3 ;
+               7,  3, 11 ];
+	
+    FV.vertices = ico.v;
+    FV.faces    = ico.f;
+end
+
+
+% -----------------
+% refine the starting shapes with subdivisions
+if maxlevel,
+    
+    % Subdivide each starting triangle (maxlevel) times
+    for level = 1:maxlevel,
+        
+        % Subdivide each triangle and normalize the new points thus
+        % generated to lie on the surface of a sphere radius r.
+        FV = mesh_refine_tri4(FV);
+        FV.vertices = sphere_project(FV.vertices,r);
+        
+        % An alternative might be to define a min distance
+        % between vertices and recurse or use fminsearch
+        
+    end
+end
+
+if winding,
+    fprintf('...returning counterclockwise vertex order (viewed from outside)\n');
+    FV.faces = FV.faces(:,[1 3 2]);
+else
+    fprintf('...returning clockwise vertex order (viewed from outside)\n');
+end
+
+t=toc; fprintf('...done (%6.2f sec)\n\n',t);
+
+return
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshaddrifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshaddrifts.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshaddrifts.m	(revision 13101)
@@ -0,0 +1,93 @@
+function md=meshaddrifts(md,riftname);
+%MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
+%
+%   Usage:
+%      md=meshaddrifts(md,riftname);
+%
+%        where md is a model with a preexisting mesh, and riftname is the name of an .exp file.
+%        The format of the riftname file is as follows: a list of pairs of closed and open contours. 
+%        The closed contour defines the envelop of the rift, the open contour that follows in the 
+%        file defines the rift. The density of the rift should be chosen carefully in the file, as it 
+%        will be used to define the rift contour density of the mesh. The open contour density will 
+%        be preserved. There can be as many pairs of closed contour and rift contour as wished.
+
+
+%read rift: 
+domains=expread(riftname,1);
+contours=domains(1:2:end);
+rifts=domains(2:2:end);
+
+%now loop over rifts: 
+for rift_i=1:length(rifts),
+	
+	%refine rift to desired resolution: 
+	contour=contours(rift_i);
+	rift=rifts(rift_i);
+	
+	delete('Meshaddrifts.Rift.exp');
+	expwrite(rift,'Meshaddrifts.Rift.Coarse.exp');
+	expcoarsen('Meshaddrifts.Rift.exp','Meshaddrifts.Rift.Coarse.exp',rift.density);
+	delete('Meshaddrifts.Rift.Coarse.exp');
+	
+	%extract model:
+	expwrite(contour,'Meshaddrifts.Contour.exp');
+	md2=modelextract(md,'Meshaddrifts.Contour.exp');
+	
+	%create domain of md2 model: 
+	md2.mesh.segments=contourenvelope(md2,'Meshaddrifts.Contour.exp');
+	domain_index=md2.mesh.segments(1,1:2);
+	while (domain_index(end)~=domain_index(1)),
+		pos=find(md2.mesh.segments(:,1)==domain_index(end));
+		domain_index(end+1)=md2.mesh.segments(pos,2);
+	end
+	
+	domain.x=md2.mesh.x(domain_index);
+	domain.y=md2.mesh.y(domain_index);
+	domain.name='Meshaddrifts.Domain.exp';
+	domain.density=1;
+	expwrite(domain,'Meshaddrifts.Domain.exp');
+	
+	%unloop domain index: used for later.
+	domain_index=domain_index(1:end-1);
+	
+	%remesh md2 using new domain outline, and rift profile: 
+	md2=meshnodensity(md2,'Meshaddrifts.Domain.exp','Meshaddrifts.Rift.exp');
+	md2=meshprocessrifts(md2);
+	
+	%plug md2 mesh into md mesh: 
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,md.mesh.numberofelements,md.mesh.numberofvertices,elconv,nodeconv,elconv2,nodeconv2]=meshplug(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,...
+								md2.mesh.elements,md2.mesh.x,md2.mesh.y,md2.mesh.z,md2.extractednodes,md2.extractedelements,domain_index);
+
+	%update md2 rifts using elconv and nodeconv, and plug them into md: 
+	md2.rifts=updateriftindexing(md2.rifts,elconv2,nodeconv2);
+	
+	for i=1:md.rifts.numrifts,
+		md.rifts.riftstruct(i)=updateriftindexing(md.rifts.riftstruct(i),elconv,nodeconv);
+	end
+	
+	if md.rifts.numrifts==0,
+		md.rifts.riftstruct=md2.rifts;
+		md.rifts.numrifts=1;
+	else
+		md.rifts.riftstruct(end+1,1)=md2.rifts;
+		md.rifts.numrifts=md.rifts.numrifts+1;
+	end
+	
+	md.mesh.segments(:,1:2)=nodeconv(md.mesh.segments(:,1:2));
+	md.mesh.segments(:,3)=elconv(md.mesh.segments(:,3));
+
+end
+
+%finish up "a la" mesh.h
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshplug.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshplug.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshplug.m	(revision 13101)
@@ -0,0 +1,89 @@
+function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain);
+%MESHPLUG - embed mesh into another one
+%     See also meshaddrifts
+
+
+%initialize elconv,nodeconv conversion tables from md mesh to new md mesh
+elconv=1:size(elements,1); elconv=elconv';
+nodeconv=1:size(x,1); nodeconv=nodeconv';
+
+%take away old elements in area of interest: 
+elements(extractedelements,:)=[];
+element_offset=size(elements,1);
+
+%update elconv after having extracted the area of interest elements
+temp_elconv=elconv; temp_elconv(extractedelements)=[];
+temp_elconvnum=1:length(temp_elconv);
+elconv(temp_elconv)=temp_elconvnum;
+elconv(extractedelements)=NaN;
+
+%initialize elconv2 and nodeconv2, conversion tables from md2 mesh to new md mesh
+elconv2=1:size(elements2,1);elconv2=elconv2'+element_offset;
+nodeconv2=(size(x,1)+1):(size(x,1)+size(x2,1)); nodeconv2=nodeconv2';
+
+extractednodes_minusborder=extractednodes;
+extractednodes_minusborder(domain)=[];
+
+x(extractednodes_minusborder)=NaN;
+y(extractednodes_minusborder)=NaN;
+
+%now, plug md2 mesh: 
+
+%first, offset all ids of md2 mesh
+elements2=elements2+length(x);
+
+%NaN border nodes in second mesh
+x2(1:length(domain))=NaN;
+y2(1:length(domain))=NaN;
+
+%redirect border nodes in elements2  to elements
+for i=1:length(domain),
+	pos=find(elements2==(i+length(x)));
+	elements2(pos)=extractednodes(domain(i));
+end
+
+%same deal for nodeconv2:
+for i=1:length(domain),
+	nodeconv2(i)=extractednodes(domain(i));
+end
+
+
+%plug elements
+elements=[elements;elements2];
+
+
+%now, increase number of nodes
+x=[x; x2];
+y=[y; y2];
+z=[z; z2];
+
+%now, get rid of NaN in x:
+while  ~isempty(find(isnan(x))),
+
+	pos=find(isnan(x));
+	node=pos(1);
+
+	%collapse node
+	x(node)=[];
+	y(node)=[];
+	z(node)=[];
+
+	%renumber all nodes > node in elements
+	pos=find(elements>node);
+	elements(pos)=elements(pos)-1;
+
+	%same deal for nodeconv2: 
+	pos=find(nodeconv2>node);
+	nodeconv2(pos)=nodeconv2(pos)-1;
+
+end
+
+numberofnodes=length(x);
+numberofelements=length(elements);
+
+%finish nodeconv: 
+temp_nodeconv=nodeconv;  temp_nodeconv(extractednodes_minusborder)=[];
+temp_nodeconvnum=1:length(temp_nodeconv);
+nodeconv(temp_nodeconv)=temp_nodeconvnum;
+nodeconv(extractednodes_minusborder)=NaN;
+
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessoutsiderifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 13101)
@@ -0,0 +1,110 @@
+function md=meshprocessoutsiderifts(md,domainoutline)
+%MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline
+%
+%   Usage:
+%      md=meshprocessoutsiderifts(md,domain)
+%
+
+
+
+%go through rifts, and figure out which ones touch the domain outline
+for i=1:md.rifts.numrifts,
+	
+	%first, flag nodes that belong to the domain outline
+	flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+
+	rift=md.rifts.riftstruct(i);
+	tips=rift.tips;
+	outsidetips=tips(find(flags(rift.tips)==0));
+
+	%we have found outsidetips, tips that touch the domain outline. go through them
+	for j=1:length(outsidetips),
+		
+		tip=outsidetips(j);
+		%find tip in the segments, take first segment (there should be 2) that holds tip, 
+		%and node_connected_to_tip is the other node on this segment:
+		tipindex=find(rift.segments(:,1)==tip); 
+		if length(tipindex),
+			tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,2);
+		else
+			tipindex=find(rift.segments(:,2)==tip); tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,1);
+		end
+
+		%ok, we have the tip node, and the first node connected to it, on the rift. Now, 
+		%identify all the elements that are connected to the tip, and that are on the same 
+		%side of the rift.
+		A=tip;
+		B=node_connected_to_tip;
+
+		elements=[];
+
+		while  flags(B), %as long as B does not belong to the domain outline, keep looking.
+			%detect elements on edge A,B:
+			edgeelements=ElementsFromEdge(md.mesh.elements,A,B);
+			%rule out those we already detected
+			already_detected=ismember(edgeelements,elements);
+			nextelement=edgeelements(find(~already_detected));
+			%add new detected element to the list of elements we are looking for.
+			elements=[elements;nextelement];
+			%new B:
+			B=md.mesh.elements(nextelement,find(~ismember(md.mesh.elements(nextelement,:),[A B])));
+		end
+		
+		%take the list of elements on one side of the rift that connect to the tip, 
+		%and duplicate the tip on them, so as to open the rift to the outside.
+		num=length(md.mesh.x)+1;
+		md.mesh.x=[md.mesh.x;md.mesh.x(tip)];
+		md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
+		md.mesh.numberofvertices=num;
+		
+		%replace tip in elements
+		newelements=md.mesh.elements(elements,:);
+		pos=find(newelements==tip);
+		newelements(pos)=num;
+		md.mesh.elements(elements,:)=newelements;
+		md.rifts.riftstruct(i).tips=[md.rifts.riftstruct(i).tips num];
+
+		%deal with segments
+		tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
+		for  k=1:length(tipsegments),
+			segment_index=tipsegments(k);
+			pos=find(md.mesh.segments(segment_index,1:2)~=tip);
+			other_node=md.mesh.segments(segment_index,pos);
+			if ~isconnected(md.mesh.elements,other_node,tip),
+				pos=find(md.mesh.segments(segment_index,1:2)==tip);
+				md.mesh.segments(segment_index,pos)=num;
+			end
+		end
+	end
+end
+
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.rifts.numrifts=length(md.rifts.riftstruct);
+md.flowequation.element_equation=3*ones(md.mesh.numberofelements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+end
+
+function flag=isconnected(elements,A,B)% {{{
+	%ISCONNECTED: are two nodes connected by a triangulation?
+	%
+	%   Usage: flag=isconnected(elements,A,B)
+	%
+	%
+
+	elements=ElementsFromEdge(elements,A,B);
+	if isempty(elements),
+		flag=0;
+	else
+		flag=1;
+	end
+end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessrifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessrifts.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshprocessrifts.m	(revision 13101)
@@ -0,0 +1,69 @@
+function md=meshprocessrifts(md,domainoutline)
+%MESHPROCESSRIFTS - process mesh when rifts are present
+%
+%   split rifts inside mesh (rifts are defined by presence of
+%   segments inside the domain outline)
+%   if domain outline is provided, check for rifts that could touch it, and open them up.
+%
+%   Usage:
+%      md=meshprocessrifts(md,domainoutline)
+%
+%   Ex: 
+%      md=meshprocessrifts(md,'DomainOutline.exp');
+%
+
+%some checks on arguments: 
+if nargout~=1,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+if nargin~=2,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+%Call MEX file
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers);
+if ~isstruct(md.rifts.riftstruct),
+	error('TriMeshProcessRifts did not find any rift');
+end
+
+%Fill in rest of fields:
+numrifts=length(md.rifts.riftstruct);
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%get coordinates of rift tips
+for i=1:numrifts,
+	md.rifts.riftstruct(i).tip1coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(1)) md.mesh.y(md.rifts.riftstruct(i).tips(1))];
+	md.rifts.riftstruct(i).tip2coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(2)) md.mesh.y(md.rifts.riftstruct(i).tips(2))];
+end
+
+%In case we have rifts that open up the domain outline, we need to open them: 
+flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+found=0;
+for i=1:numrifts,
+	if flags(md.rifts.riftstruct(i).tips(1))==0,
+		found=1;
+		break;
+	end
+	if flags(md.rifts.riftstruct(i).tips(2))==0,
+		found=1;
+		break;
+	end
+end
+if found,
+	md=meshprocessoutsiderifts(md,domainoutline);
+end
+
+%get elements that are not correctly oriented in the correct direction:
+aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+pos=find(aires<0);
+md.mesh.elements(pos,:)=[md.mesh.elements(pos,2) md.mesh.elements(pos,1) md.mesh.elements(pos,3)];
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshyamsrecreateriftsegments.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 13101)
@@ -0,0 +1,90 @@
+function md=meshyamsrecreateriftsegments(md)
+
+	%recreate rift segments: just used for yams. temporaroy routine.
+	pos_record=[];
+	if md.rifts.numrifts,
+		for i=1:md.rifts.numrifts,
+			rift=md.rifts.riftstruct(i);
+
+			%closed rifts first:
+			if length(rift.tips)==2,
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos,1);
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos,1);
+
+				%start from tip1, and build segments of this rift. 
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2];
+
+			else
+				%ok, this is a rift that opens up to the domain outline.  One tip is going to be 
+				%double, the other one, single. We are going to start from the single tip, towards the two 
+				%other doubles
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos1=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos1,1);
+				pos2=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos2,1);
+				if length(tip1)==2,
+					%swap.
+					temp=tip1; tip1=tip2; tip2=temp;
+					temp=pos1; pos1=pos2; pos2=temp;
+					pos=pos1;
+				else
+					pos=pos1;
+				end
+
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if ((riftsegs(end,2)==tip2(1)) | (riftsegs(end,2)==tip2(2))), 
+						%figure out which tip we reached
+						if riftsegs(end,2)==tip2(1), index=2; else index=1; end
+						break;
+					end
+				end
+
+				%ok, now, we start from the other tip2, towards tip1
+				pos=pos2(index);
+				pos_record=[pos_record; pos];
+				riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2(1) tip2(2)];
+
+			end
+		end
+	end
+	%take out rift segments from segments
+	md.mesh.segments(pos_record,:)=[];
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsonmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13101)
@@ -0,0 +1,26 @@
+function tips=rifttipsonmesh(md,riftoutline)
+%RIFTTIPSONMESH: identify, using a rift outline, the nodes that are tips of 
+%                rifts.
+
+%read rifts from outline file
+rifts=expread(riftoutline,1);
+
+tips=[];
+
+for i=1:length(rifts),
+	rift=rifts(i);
+
+	x_tip=rift.x(1);
+	y_tip=rift.y(1);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+	x_tip=rift.x(end);
+	y_tip=rift.y(end);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsrefine.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsrefine.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/rifttipsrefine.m	(revision 13101)
@@ -0,0 +1,26 @@
+function md=rifttipsrefine(md,filename,resolution,circleradius);
+%RIFTTIPSREFINE - refine mesh near rift tips
+%
+%   Usage:
+%      md=rifttipsrefine(md,filename,resolution,circleradius);
+
+numberofnodes=50;
+
+%take rifts, and create refinement circles around tips
+rifts=expread(filename,1);
+
+!echo -n "" > Circles.exp
+for i=1:length(rifts),
+	tip1=[rifts(i).x(1) rifts(i).y(1)];
+	tip2=[rifts(i).x(end) rifts(i).y(end)];
+	%create circle around tip
+	expcreatecircle('Circle1.exp',tip1(1),tip1(2),circleradius,numberofnodes);
+	expcreatecircle('Circle2.exp',tip2(1),tip2(2),circleradius,numberofnodes);
+	!cat Circles.exp Circle1.exp Circle2.exp > Circles2.exp
+	!mv Circles2.exp Circles.exp
+	!rm -rf Circle1.exp Circle2.exp
+end
+
+md=meshexprefine(md,'Circles.exp',resolution);
+
+system('rm -rf Circles.exp');
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/updateriftindexing.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/updateriftindexing.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/rifts/updateriftindexing.m	(revision 13101)
@@ -0,0 +1,11 @@
+function rift=updateriftindexing(rift,elconv,nodeconv)
+%UPDATERIFTINDEXING - update rift indexing, using mesh to new mesh conversion tables
+%     See also meshaddrift
+
+rift.segments(:,1:2)=nodeconv(rift.segments(:,1:2));
+rift.segments(:,3)=elconv(rift.segments(:,3));
+rift.pairs=elconv(rift.pairs);
+rift.tips=nodeconv(rift.tips);
+
+rift.penaltypairs(:,1:2)=nodeconv(rift.penaltypairs(:,1:2));
+rift.penaltypairs(:,3:4)=elconv(rift.penaltypairs(:,3:4));
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/roundmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/roundmesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/roundmesh.m	(revision 13101)
@@ -0,0 +1,34 @@
+function md=roundmesh(md,radius,resolution)
+%ROUNDMESH - create an unstructured round mesh 
+%
+%   This script will generate a structured round mesh
+%   - radius     : specifies the radius of the circle in meters
+%   - resolution : specifies the resolution in meters
+%
+%   Usage:
+%      md=roundmesh(md,radius,resolution)
+
+%First we have to create the domain outline 
+
+%Get number of points on the circle
+pointsonedge=floor((2*pi*radius) / resolution);
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
+theta=(0:2*pi/pointsonedge:2*pi*(1-1/pointsonedge))';
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+A=struct('x',x_list,'y',y_list,'density',1);
+expwrite(A,'RoundDomainOutline.exp');
+
+%Call Bamg
+md=triangle(md,'RoundDomainOutline.exp',resolution);
+%md=bamg(md,'domain','RoundDomainOutline.exp','hmin',resolution);
+
+%move the closest node to the center
+[mini pos]=min(md.mesh.x.^2+md.mesh.y.^2);
+md.mesh.x(pos)=0;
+md.mesh.y(pos)=0;
+
+%delete domain
+delete('RoundDomainOutline.exp')
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/squaremesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/squaremesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/squaremesh.m	(revision 13101)
@@ -0,0 +1,78 @@
+function md=squaremesh(md,Lx,Ly,nx,ny)
+%SQUAREMESH - create a structured square mesh 
+%
+%   This script will generate a structured square mesh
+%   Lx and Ly are the dimension of the domain (in meters)
+%   nx anx ny are the number of nodes in the x and y direction
+%   The coordinates x and y returned are in meters.
+%
+%   Usage:
+%      [md]=squaremesh(md,Lx,Ly,nx,ny)
+
+%get number of elements and number of nodes
+nel=(nx-1)*(ny-1)*2;
+nods=nx*ny;
+
+%initialization
+segments=zeros(0,3);
+index=zeros(nel,3);
+x=zeros(nx*ny,1);
+y=zeros(nx*ny,1);
+
+%create coordinates
+for n=1:nx,
+	for m=1:ny,
+		x((n-1)*ny+m)=(n-1);
+		y((n-1)*ny+m)=(m-1);
+	end
+end
+
+%create index
+for n=1:(nx-1)
+	for m=1:(ny-1),
+		A=(n-1)*ny+m;
+		B=A+1;
+		C=n*ny+m;
+		D=C+1;
+		index((n-1)*(ny-1)*2+2*(m-1)+1,:)=[A C B];
+		index((n-1)*(ny-1)*2+2*m,:)=[B C D];
+	end
+end
+
+%Scale  x and y
+x=x/max(x)*Lx;
+y=y/max(y)*Ly;
+
+%create segments
+segments=zeros(2*(nx-1)+2*(ny-1),3);
+%left edge:
+segments(1:ny-1,:)=[[2:ny]' [1:ny-1]' 2*[1:ny-1]'-1];
+%right edge:
+segments(ny:2*(ny-1),:)=[[ny*(nx-1)+1:nx*ny-1]' [ny*(nx-1)+2:nx*ny]' 2*[(ny-1)*(nx-2)+1:(nx-1)*(ny-1)]'];
+%front edge:
+segments(2*(ny-1)+1:2*(ny-1)+(nx-1),:)=[[2*ny:ny:ny*nx]' [ny:ny:ny*(nx-1)]' [2*(ny-1):2*(ny-1):2*(nx-1)*(ny-1)]'];
+%back edge
+segments(2*(ny-1)+(nx-1)+1:2*(nx-1)+2*(ny-1),:)=[[1:ny:(nx-2)*ny+1]' [ny+1:ny:ny*(nx-1)+1]' [1:2*(ny-1):2*(nx-2)*(ny-1)+1]'];
+
+%plug coordinates and nodes
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.z=zeros(nods,1);
+md.mesh.numberofvertices=nods;
+md.mesh.vertexonboundary=zeros(nods,1);md.mesh.vertexonboundary(segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(nods,1);
+md.mesh.vertexonsurface=ones(nods,1);
+
+%plug elements
+md.mesh.elements=index;
+md.mesh.segments=segments;
+md.mesh.numberofelements=nel;
+md.mesh.elementonbed=ones(nel,1);
+md.mesh.elementonsurface=ones(nel,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%plug other field
+md.mesh.dimension=2;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.m	(revision 13101)
@@ -0,0 +1,82 @@
+function md=triangle(md,domainname,varargin)
+%TRIANGLE - create model mesh using the triangle package
+%
+%   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+%   where md is a @model object, domainname is the name of an Argus domain outline file, 
+%   and resolution is a characteristic length for the mesh (same unit as the domain outline
+%   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+%
+%   Usage:
+%      md=triangle(md,domainname,resolution)
+%   or md=triangle(md,domainname,riftname, resolution)
+%
+%   Examples:
+%      md=triangle(md,'DomainOutline.exp',1000);
+%      md=triangle(md,'DomainOutline.exp','Rifts.exp',1500);
+
+%Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would 
+%be made of 1000*1000 area squares). 
+if (nargin==3),
+	resolution=varargin{1};
+	riftname='';
+end
+if (nargin==4),
+	riftname=varargin{1};
+	resolution=varargin{2};
+end
+
+%Check that mesh was not already run, and warn user: 
+if md.mesh.numberofelements~=0,
+	choice=input('This model already has a mesh. Are you sure you want to go ahead? (y/n)','s');
+	if ~strcmp(choice,'y')
+		disp('no meshing done ... exiting');
+		return
+	end
+end
+
+area=resolution^2;
+
+%Mesh using TriMesh
+[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area);
+
+%check that all the created nodes belong to at least one element
+orphan=find(~ismember([1:length(x)],sort(unique(elements(:)))));
+for i=1:length(orphan),
+	disp('WARNING: removing orphans');
+	%get rid of the orphan node i
+	%update x and y
+	x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+	y=[y(1:orphan(i)-(i-1)-1); y(orphan(i)-(i-1)+1:end)];
+	%update elements
+	pos=find(elements>orphan(i)-(i-1));
+	elements(pos)=elements(pos)-1;
+	%update segments
+	pos1=find(segments(:,1)>orphan(i)-(i-1));
+	pos2=find(segments(:,2)>orphan(i)-(i-1));
+	segments(pos1,1)=segments(pos1,1)-1;
+	segments(pos2,2)=segments(pos2,2)-1;
+end
+
+%plug into md
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.elements=elements;
+md.mesh.segments=segments;
+md.mesh.segmentmarkers=segmentmarkers;
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/mesh/triangle.py	(revision 13101)
@@ -0,0 +1,56 @@
+from numpy import *
+import TriMesh as tm
+import NodeConnectivity as nc
+import ElementConnectivity as ec
+
+def triangle(md, domainname, resolution,riftname=''):
+	#TRIANGLE - create model mesh using the triangle package
+	#
+	#   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+	#   where md is a @model object, domainname is the name of an Argus domain outline file, 
+	#   and resolution is a characteristic length for the mesh (same unit as the domain outline
+	#   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+	#
+	#   Usage:
+	#      md=triangle(md,domainname,resolution)
+	#   or md=triangle(md,domainname, resolution, riftname)
+	#
+	#   Examples:
+	#      md=triangle(md,'DomainOutline.exp',1000);
+	#      md=triangle(md,'DomainOutline.exp',1000,'Rifts.exp');
+
+
+	#Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would 
+	#be made of 1000*1000 area squares). 
+
+	#Check that mesh was not already run, and warn user: 
+	if md.mesh.numberofelements != 0.:
+		choice = input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
+		if choice != 'y':
+			print 'no meshing done ... exiting'
+			return []
+		
+	area = resolution**2.
+
+	#Mesh using TriMesh
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=tm.TriMesh(domainname,riftname,area)
+
+
+	#Fill in rest of fields:
+	md.mesh.numberofelements = len(md.mesh.elements)
+	md.mesh.numberofvertices = len(md.mesh.x)
+	md.mesh.z = zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1] = 1.
+	md.mesh.vertexonbed = ones(md.mesh.numberofvertices)
+	md.mesh.vertexonsurface = ones(md.mesh.numberofvertices)
+	md.mesh.elementonbed = ones(md.mesh.numberofelements)
+	md.mesh.elementonsurface = ones(md.mesh.numberofelements)
+
+	#Now, build the connectivity tables for this mesh.
+	[md.mesh.vertexconnectivity]= nc.NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
+	[md.mesh.elementconnectivity] = ec.ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
+	
+	#type of model
+	md.mesh.dimension = 2.
+	return md
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/MatlabFuncs.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/MatlabFuncs.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/MatlabFuncs.py	(revision 13101)
@@ -0,0 +1,52 @@
+def oshostname():
+	import socket
+
+	return socket.gethostname().lower().split('.')[0]
+
+def strcmp(s1,s2):
+
+	if s1 == s2:
+		return True
+	else:
+		return False
+
+def strncmp(s1,s2,n):
+
+	if s1[0:n] == s2[0:n]:
+		return True
+	else:
+		return False
+
+def strcmpi(s1,s2):
+
+	if s1.lower() == s2.lower():
+		return True
+	else:
+		return False
+
+def strncmpi(s1,s2,n):
+
+	if s1.lower()[0:n] == s2.lower()[0:n]:
+		return True
+	else:
+		return False
+
+def ismember(a,s):
+	import numpy
+
+	if not isinstance(s,(tuple,list,dict,numpy.ndarray)):
+		s=[s]
+
+	if not isinstance(a,(tuple,list,dict,numpy.ndarray)):
+		a=[a]
+
+	if not isinstance(a,numpy.ndarray):
+		b=[item in s for item in a]
+
+	else:
+		b=numpy.empty_like(a)
+		for i,item in enumerate(a.flat):
+			b.flat[i]=item in s
+
+	return b
+
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.m	(revision 13101)
@@ -0,0 +1,154 @@
+function fielddisplay(md,name,comment)
+%FIELDDISPLAY - display model field
+%
+%   Usage:
+%      fielddisplay(md,offset,name,comment)
+
+	%get field
+	field=md.(name);
+
+	%disp corresponding line as a function of field type (offset set as 9 spaces)
+	parsedisplay('         ',name,field,comment);
+
+end %function
+
+function parsedisplay(offset,name,field,comment); %{{{
+
+	%string
+	if ischar(field),
+
+		if length(field)>30;
+			displayunit(offset,name,'not displayed',comment),
+		else
+			displayunit(offset,name,['''' field ''''],comment),
+		end
+
+	%numeric
+	elseif isnumeric(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%double
+		if max(fieldsize)==1,
+			displayunit(offset,name,num2str(field),comment),
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+	%logical
+	elseif islogical(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%single value
+		if max(fieldsize)==1,
+			if (field)
+				displayunit(offset,name,'true',comment),
+			else
+				displayunit(offset,name,'false',comment),
+			end
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+		%structure
+	elseif isstruct(field),
+		if ~isempty(fields(field))
+			displayunit(offset,name,'(structure)',comment),
+			struct_display(field,[offset '   ']),
+		else
+			displayunit(offset,name,'N/A',comment),
+		end
+
+	%cell
+	elseif iscell(field),
+		cell_display(offset,name,field,comment),
+
+	else
+		displayunit(offset,name,'not displayed',comment),
+
+	end
+end%}}}
+
+function struct_display(structure,offset) % {{{
+
+	structure_fields=fields(structure);
+
+	for i=1:length(structure_fields),
+
+		%get current field
+		field=structure.(structure_fields{i});
+
+		%recursive call if necessary
+		if isstruct(field),
+			displayunit(offset,structure_fields{i},'(structure)',''),
+			struct_display(field,[offset '   ']);
+
+		%display value
+		else
+			parsedisplay(offset,structure_fields{i},field,'');
+		end
+	end
+end% }}}
+function cell_display(offset,name,field,comment) % {{{
+
+	%initialization
+	string='{';
+
+	%go through the cell and fill string
+	if length(field)<5;
+		for i=1:length(field),
+			if ischar(field{i}),
+				string=[string ''''  field{i} ''','];
+			elseif (isnumeric(field{i}) & length(field{i})==1)
+				string=[string num2str(field{i}) ',' ];
+			else
+				string='{';
+				break
+			end
+		end
+	end
+	if strcmp(string,'{'),
+		string=['(' num2str(size(field,1)) 'x' num2str(size(field,2)) ')'];
+	else
+		string=[string(1:end-1) '}'];
+	end
+
+	%call displayunit
+	displayunit(offset,name,string,comment);
+end% }}}
+function displayunit(offset,name,characterization,comment),% {{{
+
+	%take care of name
+	if length(name)>23,
+		name=[name(1:20) '...'];
+	end
+
+	%take care of characterization
+	if (strcmp(characterization,['''' '''']) | strcmp(characterization,'NaN')),
+		characterization='N/A';
+	end
+	if length(characterization)>15,
+		characterization=[characterization(1:12) '...'];
+	end
+
+	%print
+	if isempty(comment)
+		disp(sprintf('%s%-23s: %-15s',offset,name,characterization));
+	else
+		if ischar(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment));
+		elseif iscell(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment{1}));
+			for i=2:length(comment),
+				disp(sprintf('%s%-23s  %-15s    %s',offset,'','',comment{i}));
+			end
+		else
+			error('fielddisplay error message: format for comment not supportet yet');
+		end
+	end
+end% }}}
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/fielddisplay.py	(revision 13101)
@@ -0,0 +1,102 @@
+#Module import 
+from math import isnan
+
+
+def fielddisplay(md,name,comment):
+#FIELDDISPLAY - display model field
+#
+#   Usage:
+#      fielddisplay(md,name,comment)
+
+	#get field
+	field=getattr(md,name)
+
+	#disp corresponding line as a function of field type (offset set as 9 spaces)
+	return parsedisplay("         ",name,field,comment);
+
+#parsedisplay{{{ 
+def  parsedisplay(offset,name,field,comment):
+
+	#string
+	if isinstance(field,(str,unicode)):
+		if len(field)>30:
+			string=displayunit(offset,name,"not displayed",comment)
+		else:
+			string=displayunit(offset,name,field,comment)
+
+	#numeric
+	elif isinstance(field, (int,long)):
+		string=displayunit(offset,name,"%i" % (field),comment) 
+
+	elif isinstance(field, complex):
+		raise RuntimeError("fielddisplay cannot handle complex numbers")
+
+	elif isinstance(field, float):
+		string=displayunit(offset,name,"%g"%(field),comment)
+
+	#logical
+	elif isinstance(field,bool):
+		if field:
+			string=displayunit(offset,name,"true",comment)
+		else:
+			string=displayunit(offset,name,"false",comment)
+	
+	elif isinstance(field,dict):
+		if not field:
+			string=displayunit(offset,name,'N/A',comment)
+		else:
+			string=displayunit(offset,name,'(dictionary)',comment)
+			for key in field.keys():
+				string="%s\n%s"%(string,parsedisplay(offset + '   ',key,field[key],''))
+
+	elif isinstance(field,list):
+		if not field:
+			string=displayunit(offset,name,'N/A',comment),
+		else:
+			string=displayunit(offset,name,'(structure)',comment)
+			for i in range(len(field)):
+				string="%s\n%s"%(string,displayunit(offset + '   ',name,field[i],comment))
+	#cell
+	#elif  iscell(field):
+	#	cell_display(offset,name,field,comment),
+
+	else:
+		string=displayunit(offset,name,"not displayed",comment)
+		
+	return string
+
+#}}}
+#displayunit {{{
+def  displayunit(offset,name,characterization,comment):
+
+	#take care of name
+	if len(name)>23:
+		name="%s..." % (name[:19])
+	
+	#take care of characterization
+	if characterization=="":
+		characterization="N/A"
+	
+	if characterization=="nan":
+		characterization="N/A"
+	
+	if len(characterization)>15:
+		characterization="%s%s" % (characterization[:11],"...")
+	
+	#print
+	if not comment:
+		string="%s%-23s: %-15s" % (offset,name,characterization)
+	else:
+		if isinstance(comment,(str,unicode)):
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment)
+		elif isinstance(comment,list):
+			print(comment)
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment[0])
+			for i in range(1,len(comment)):
+				string2="%s%-23s  %-15s    %s" %(offset,"","",comment[i])
+				string="%s\n%s"%(string,string2)
+		else:
+			raise RuntimeError("fielddisplay error message: format for comment not supportet yet")
+
+	return string
+#}}}
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.m	(revision 13101)
@@ -0,0 +1,15 @@
+function returnvalue=isnans(array)
+%ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+%
+%  Usage:    isnans(array)
+%
+%  See also : ISNAN 
+
+
+if isstruct(array), 
+	returnvalue=0;
+elseif iscell(array)
+	returnvalue=0;
+else
+	returnvalue=isnan(array);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/isnans.py	(revision 13101)
@@ -0,0 +1,18 @@
+import numpy
+
+def isnans(array):
+	"""
+	ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+
+	   Usage:    isnans(array)
+
+	      See also : ISNAN 
+	"""
+
+	if   isinstance(array,(tuple,list,dict)): 
+		returnvalue=0
+	else:
+		returnvalue=numpy.isnan(array)
+
+	return returnvalue
+
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/issmdoc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/issmdoc.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/issmdoc.m	(revision 13101)
@@ -0,0 +1,15 @@
+%Quick documentation for ISSM
+
+%First get ISSM tier: 
+ISSM_DIR=issmdir();
+
+disp(sprintf('\n%s','  A comprehensive documentation is available on http://issm.jpl.nasa.gov'));
+disp(sprintf('\n%s','  Example: how to create a square ice shelf'));
+disp(sprintf('%s','	   go to ',ISSM_DIR,'/examples/SquareIceshelf'));
+disp(sprintf('%s','	   md=model;                                %creates a new empty model structure'));
+disp(sprintf('%s','	   md=triangle(md,''DomainOutline.exp'',50000);   %creates a mesh of the domain outline with a resolution of 50000m'));
+disp(sprintf('%s','	   md=setmask(md,''all'','''');               %defines the glacier system as an ice shelf (no island)'));
+disp(sprintf('%s','	   md=parameterize(md,''Square.par'');        %fills all the other fields of the model'));
+disp(sprintf('%s','	   md=setflowequation(md,''macayeal'',''all''); %defines all elements as MacAyeal''s'));
+disp(sprintf('%s','	   md=solve(md,DiagnosticSolutionEnum());   %generate the velocity field'));
+disp(sprintf('%s','	   plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);    %displays the velocity (type plotdoc for plotmodel help)'));
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/netcdf2struct.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/netcdf2struct.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/netcdf2struct.m	(revision 13101)
@@ -0,0 +1,166 @@
+function S=netcdf2struct(File)
+%NETCDF2STRUCT - load netcdf file and convert to a matlab structure
+%
+%   Usage:
+%      S=netcdf2struct(File);
+
+%Read netcdf file
+data=readnetcdf(File);
+
+%initialize output
+S=struct();
+
+%All the variables are in VarArray field
+variables=data.VarArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(squeeze(variables(i).Data));
+	S.(fieldname)=fieldvalue;
+end
+
+%All the variables are in AttArray field
+variables=data.AttArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(variables(i).Val);
+	S.(fieldname)=fieldvalue;
+end
+end
+
+function S = readnetcdf(File,varargin)
+% Function to read NetCDF files
+%   S = netcdf(File)
+% Input Arguments
+%   File = NetCDF file to read
+% Optional Input Arguments:
+%   'Var',Var - Read data for VarArray(Var), default [1:length(S.VarArray)]
+%   'Rec',Rec - Read data for Record(Rec), default [1:S.NumRecs]
+% Output Arguments:
+%   S    = Structure of NetCDF data organised as per NetCDF definition
+% Notes:
+%   Only version 1, classic 32bit, NetCDF files are supported. By default
+% data are extracted into the S.VarArray().Data field for all variables.
+% To read the header only call S = netcdf(File,'Var',[]);
+%
+% SEE ALSO
+% ---------------------------------------------------------------------------
+S = [];
+
+try
+   if exist(File,'file') fp = fopen(File,'r','b');
+   else fp = []; error('File not found'); end
+   if fp == -1   error('Unable to open file'); end
+
+% Read header
+   Magic = fread(fp,4,'uint8=>char');
+   if strcmp(Magic(1:3),'CDF') error('Not a NetCDF file'); end
+   if uint8(Magic(4))~=1       error('Version not supported'); end
+   S.NumRecs  = fread(fp,1,'uint32=>uint32');
+   S.DimArray = DimArray(fp);
+   S.AttArray = AttArray(fp);
+   S.VarArray = VarArray(fp);
+
+% Setup indexing to arrays and records
+   Var = ones(1,length(S.VarArray));
+   Rec = ones(1,S.NumRecs);
+   for i = 1:2:length(varargin)
+      if     strcmp(upper(varargin{i}),'VAR') Var=Var*0; Var(varargin{i+1})=1;
+      elseif strcmp(upper(varargin{i}),'REC') Rec=Rec*0; Rec(varargin{i+1})=1;
+      else error('Optional input argument not recognised'); end
+   end
+   if sum(Var)==0 fclose(fp); return; end
+
+% Read non-record variables
+   Dim = double(cat(2,S.DimArray.Dim));
+   ID  = double(cat(2,S.VarArray.Type));
+
+   for i = 1:length(S.VarArray)
+      D = Dim(S.VarArray(i).DimID+1); N = prod(D); RecID{i}=find(D==0);
+      if isempty(RecID{i})
+         if length(D)==0 D = [1,1]; N = 1; elseif length(D)==1 D=[D,1]; end
+         if Var(i)
+            S.VarArray(i).Data = ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D);
+            fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8');
+         else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+      else S.VarArray(i).Data = []; end
+   end
+
+% Read record variables
+   for k = 1:S.NumRecs
+      for i = 1:length(S.VarArray)
+         if ~isempty(RecID{i})
+            D = Dim(S.VarArray(i).DimID+1); D(RecID{i}) = 1; N = prod(D);
+            if length(D)==1 D=[D,1]; end
+            if Var(i) & Rec(k)
+               S.VarArray(i).Data = cat(RecID{i},S.VarArray(i).Data,...
+                  ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D));
+               if N > 1 fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); end
+            else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+         end
+      end
+   end
+
+   fclose(fp);
+catch
+   Err = lasterror; fprintf('%s\n',Err.message);
+   if ~isempty(fp) && fp ~= -1 fclose(fp); end
+end
+
+% ---------------------------------------------------------------------------------------
+% Utility functions
+
+function S = Size(ID)
+% Size of NetCDF data type, ID, in bytes
+   S = subsref([1,1,2,4,4,8],struct('type','()','subs',{{ID}}));
+
+function T = Type(ID)
+% Matlab string for CDF data type, ID
+   T = subsref({'int8','char','int16','int32','single','double'},...
+               struct('type','{}','subs',{{ID}}));
+
+function N = Pad(Num,ID)
+% Number of elements to read after padding to 4 bytes for type ID
+   N = (double(Num) + mod(4-double(Num)*Size(ID),4)/Size(ID)).*(Num~=0);
+
+function S = String(fp)
+% Read a CDF string; Size,[String,[Padding]]
+   S = fread(fp,Pad(fread(fp,1,'uint32=>uint32'),1),'uint8=>char').';
+
+function A = ReOrder(A,S)
+% Rearrange CDF array A to size S with matlab ordering
+   A = permute(reshape(A,fliplr(S)),fliplr(1:length(S)));
+
+function S = DimArray(fp)
+% Read DimArray into structure
+   if fread(fp,1,'uint32=>uint32') == 10 % NC_DIMENSION
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         S(i).Dim = fread(fp,1,'uint32=>uint32');
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = AttArray(fp)
+% Read AttArray into structure
+   if fread(fp,1,'uint32=>uint32') == 12 % NC_ATTRIBUTE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         ID       = fread(fp,1,'uint32=>uint32');
+         Num      = fread(fp,1,'uint32=>uint32');
+         S(i).Val = fread(fp,Pad(Num,ID),[Type(ID),'=>',Type(ID)]).';
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = VarArray(fp)
+% Read VarArray into structure
+   if fread(fp,1,'uint32=>uint32') == 11 % NC_VARIABLE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str      = String(fp);
+         Num           = double(fread(fp,1,'uint32=>uint32'));
+         S(i).DimID    = double(fread(fp,Num,'uint32=>uint32'));
+         S(i).AttArray = AttArray(fp);
+         S(i).Type     = fread(fp,1,'uint32=>uint32');
+         S(i).VSize    = fread(fp,1,'uint32=>uint32');
+         S(i).Begin    = fread(fp,1,'uint32=>uint32'); % Classic 32 bit format only
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.m	(revision 13101)
@@ -0,0 +1,23 @@
+function [i1,i2]=parallelrange(rank,numprocs,globalsize)
+%PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+%
+%   Usage: 
+%      [i1,i1]=parallelrange(rank,numprocs,globalsize)
+
+num_local_rows=zeros(numprocs,1);
+
+for i=1:numprocs,
+	%we use floor. we under distribute rows. The rows left  are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows(i)=floor(globalsize/numprocs);
+end
+
+
+%There may be some rows left. Distribute evenly.
+row_rest=globalsize - numprocs*floor(globalsize/numprocs);
+
+for i=1:row_rest,
+	num_local_rows(i)=num_local_rows(i)+1;
+end
+
+i1=sum(num_local_rows(1:rank-1))+1;
+i2=i1+num_local_rows(rank)-1;
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/parallelrange.py	(revision 13101)
@@ -0,0 +1,25 @@
+#! /usr/bin/env python
+def parallelrange(rank,numprocs,globalsize):
+	"""
+	PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+ 
+	   Usage: 
+	      i1,i2=parallelrange(rank,numprocs,globalsize)
+	"""
+
+	#We use floor. we under distribute rows. The rows left are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows=[int(globalsize/numprocs) for i in xrange(numprocs)]
+
+	#There may be some rows left. Distribute evenly.
+	row_rest=globalsize - numprocs*int(globalsize/numprocs)
+
+	for i in xrange(row_rest):
+		num_local_rows[i]=num_local_rows[i]+1
+
+	i1=0
+	for i in xrange(rank-1):
+		i1+=num_local_rows[i]
+	i2=i1+num_local_rows[rank-1]-1
+
+	return i1,i2
+
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/round_ice.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/round_ice.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/round_ice.m	(revision 13101)
@@ -0,0 +1,36 @@
+function new_x=round_ice(x,numnonzeros)
+%ROUND_ICE - rounds up x so that it has only numnonzeros non zero digits
+%
+%   numnonzeros must be an integer larger or equal to 1
+%
+%   Usage:
+%      new_x=round_ice(x,numnonzeros)
+
+%some checks
+if (nargin ~=2 | nargout>1),
+	error('round_ice usage: new_x=round_ice(x,numonzeros)');
+end
+if ~isnumeric(x)
+	error('round_ice error message: x must be a number and numzeros an integer');
+end
+if round(numnonzeros)~=numnonzeros
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if any(numnonzeros<1)
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if (length(numnonzeros)~=1 & size(numnonzeros)~=size(x))
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1 or a list of integers of length length(x)')
+end
+
+%figure out how long x is
+lengthx=ceil(log10(abs(x)));
+
+%if x contains 0, lengthx=-Inf
+lengthx(isinf(lengthx))=1;
+
+%get its sign
+si=sign(x);
+
+%rule out zeros
+new_x=si.*round(abs(x).*10.^(-lengthx+numnonzeros)).*10.^(lengthx-numnonzeros);
Index: /issm/branches/trunk-jpl-damage/src/m/miscellaneous/structtoobj.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/miscellaneous/structtoobj.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/miscellaneous/structtoobj.m	(revision 13101)
@@ -0,0 +1,16 @@
+function obj=structtoobj(obj,S),
+%Convert struct to object
+
+	%Get object and structure fields
+	structfields=fields(S);
+	objprops    =properties(class(obj));
+
+	%recover object properties
+	for i=1:length(structfields),
+		fieldname =structfields{i};
+		if ismember(fieldname,objprops),
+			fieldvalue=getfield(S,fieldname);
+			obj=setfield(obj,fieldname,fieldvalue);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/flaimdir.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/flaimdir.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/flaimdir.m	(revision 13101)
@@ -0,0 +1,7 @@
+function FLAIM_DIR=flaimdir()
+%ISSMDIR - Get FLAIM installation directory
+%
+%   Usage:
+%      FLAIM_DIR=flaimdir()
+
+FLAIM_DIR=[issmdir() '/externalpackages/flaim/install'];
Index: /issm/branches/trunk-jpl-damage/src/m/os/ismumps.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/ismumps.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/ismumps.m	(revision 13101)
@@ -0,0 +1,33 @@
+function flag=ismumps()
+%ISMUMPS - figure out if MUMPS package was compiled with ISSM
+%
+%   Usage:
+%       flag=ismumps();
+
+
+configfile=[issmdir() '/bin/config.h']; %should find it in the install target
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+flag=2;
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25),
+		flag=0;
+		break;
+	end
+	if  strncmp(tline,'#define _HAVE_MUMPS_',20),
+		flag=1;
+		break;
+	end
+end
+fclose(fid);
+if flag==2,
+	error('could not determine whether MUMPS was or was not compiled');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/ismumps.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/ismumps.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/ismumps.py	(revision 13101)
@@ -0,0 +1,37 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def ismumps():
+	"""
+	ISMUMPS - figure out if MUMPS package was compiled with ISSM
+ 
+	   Usage:
+	      flag=ismumps();
+	"""
+
+	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	flag=2
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOError("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25):
+			flag=0
+			break
+		if  strncmp(tline,'#define _HAVE_MUMPS_',20):
+			flag=1
+			break
+
+	fid.close()
+	if flag==2:
+		raise RuntimeError("could not determine whether MUMPS was or was not compiled.")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.m	(revision 13101)
@@ -0,0 +1,33 @@
+function flag=ispetsc()
+%ISPETSC - figure out if PETSC package was compiled with ISSM
+%
+%   Usage:
+%       flag=ispetsc();
+
+
+configfile=[issmdir() '/bin/config.h']; %should find it in the install target
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+flag=2;
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25),
+		flag=0;
+		break;
+	end
+	if  strncmp(tline,'#define _HAVE_PETSC_',20),
+		flag=1;
+		break;
+	end
+end
+fclose(fid);
+if flag==2,
+	error('could not determine whether PETSC was or was not compiled');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/ispetsc.py	(revision 13101)
@@ -0,0 +1,37 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def ispetsc():
+	"""
+	ISPETSC - figure out if PETSC package was compiled with ISSM
+ 
+	   Usage:
+	      flag=ispetsc();
+	"""
+
+	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	flag=2
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOError("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25):
+			flag=0
+			break
+		if  strncmp(tline,'#define _HAVE_PETSC_',20):
+			flag=1
+			break
+
+	fid.close()
+	if flag==2:
+		raise RuntimeError("could not determine whether PETSC was or was not compiled.")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpin.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpin.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpin.m	(revision 13101)
@@ -0,0 +1,48 @@
+function issmbbftpin(host, login,port,numstreams,path, packages)
+%BBFTPIN get packages from host, using bbftp. assuming unix system here.
+%
+%   usage: scpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; get Antarctica.outbin' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; '];
+	for i=1:length(packages),
+		command=[command 'get ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+
+	%check bbftp worked
+	for i=1:numel(packages),
+		if ~exist(['./' packages{i}]),
+			error('scpin error message: could not call scp on *nix system');
+		end
+	end
+
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpout.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpout.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmbbftpout.m	(revision 13101)
@@ -0,0 +1,30 @@
+function issmbbftpout(host,path,login,port,numstreams,packages)
+%BBFTPOUT put packages onto host, using bbftp. assuming unix system here.
+%
+%   usage: bbftpout(host,path,login,port,numstream,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; put Antarctica.tar.gz' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; ']
+	for i=1:length(packages),
+		command=[command 'put ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmdir.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmdir.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmdir.m	(revision 13101)
@@ -0,0 +1,18 @@
+function ISSM_DIR=issmdir()
+%ISSMDIR - Get ISSM_DIR environment variable
+%
+%   Usage:
+%      ISSM_DIR=issmdir()
+
+if ~ispc,
+	ISSM_DIR =getenv('ISSM_DIR');
+else
+	ISSM_DIR =getenv('ISSM_DIR_WIN');
+	if strcmpi(ISSM_DIR(end),'/') | strcmpi(ISSM_DIR(end),'\'),
+		ISSM_DIR = ISSM_DIR(1:end-1); %shave off the last '/'
+	end
+end
+
+if (isempty(ISSM_DIR)),
+	error('issmdir error message: ''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmdir.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmdir.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmdir.py	(revision 13101)
@@ -0,0 +1,24 @@
+import platform
+import os
+from MatlabFuncs import *
+
+def issmdir():
+	"""
+	ISSMDIR - Get ISSM_DIR environment variable
+ 
+	   Usage:
+	      ISSM_DIR=issmdir()
+	"""
+
+	if 'Windows' not in platform.system():
+		ISSM_DIR =os.environ['ISSM_DIR']
+	else:
+		ISSM_DIR =os.environ['ISSM_DIR_WIN']
+		if strcmpi(ISSM_DIR[-1],'/') or strcmpi(ISSM_DIR[-1],'\\'):
+			ISSM_DIR = ISSM_DIR[:-1]    #shave off the last '/'
+
+	if not ISSM_DIR:
+		raise RuntimeError("issmdir error message: 'ISSM_DIR' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!")
+
+	return ISSM_DIR
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.m	(revision 13101)
@@ -0,0 +1,78 @@
+function issmscpin(host, login,port,path, packages)
+%ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	if ispc,
+		%use the putty project pscp.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpin error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' host ':' path '/' packages{i} ' ./']);
+			if status, 
+				error('issmscpin error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%string to copy multiple files using scp: 
+		if numel(packages)==1,
+			string=packages{1};
+		else
+			string='\{';
+			for i=1:numel(packages)-1,
+				string=[string packages{i} ','];
+			end
+			string=[string packages{end} '\}'];
+		end
+
+
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' login '@localhost:' path '/' string ' ./']);
+		else
+			eval(['!scp ' login '@' host ':' path '/' string ' ./']);
+		end
+		
+		%check scp worked
+		for i=1:numel(packages),
+			if ~exist(['./' packages{i}]),
+				error('issmscpin error message: could not call scp on *nix system');
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmscpin.py	(revision 13101)
@@ -0,0 +1,75 @@
+import socket
+import platform
+import subprocess
+import os
+import shutil
+from MatlabFuncs import *
+
+def issmscpin(host, login,port,path, packages):
+	"""
+	ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpin(host,packages,path)
+	"""
+
+	#first get hostname
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+	#remove warnings in case the files do not exist
+	for package in packages:
+		try:
+			os.remove(package)
+		except OSError as e:
+			pass
+
+	#if hostname and host are the same, do a simple copy
+	if strcmpi(hostname,host):
+
+		for package in packages:
+			try:
+				shutil.copy(os.path.join(path,package),os.getcwd())    #keep going, even if success=0
+			except OSError as e:
+				pass
+
+	else:
+
+		if 'Windows' in platform.system():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmscpin error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s:%s %s' % (ISSM_DIR,username,key,host,os.path.join(path,package),os.getcwd()),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("issmscpin error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#string to copy multiple files using scp: 
+			if len(packages)==1:
+				string=packages[0]
+			else:
+				string='{'
+				for package in packages:
+					string+=packages[i]+','
+				string=string[:-1]+'}'
+
+			if port:
+				subprocess.call('scp -P %d %s@localhost:%s %s' % (port,login,os.path.join(path,string),os.getcwd),shell=True)
+			else:
+				subprocess.call('scp %s@%s:%s %s' % (login,host,os.path.join(path,string),os.getcwd),shell=True)
+		
+			#check scp worked
+			for package in packages:
+				if not os.path.exists(os.path.join('.',package)):
+					raise OSError("issmscpin error message: could not call scp on *nix system.")
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.m	(revision 13101)
@@ -0,0 +1,57 @@
+function issmscpout(host,path,login,port,packages)
+%ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpout(host,path,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	if ispc,
+		%use the putty project pscp.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpout error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' packages{i} ' ' host ':' path]);
+			if status, 
+				error('issmscpout error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%create string of packages being sent
+		string='';
+		for i=1:numel(packages),
+			string=[string ' ' packages{i}];
+		end
+		string=[string ' '];
+		
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
+		else
+			eval(['!scp ' string ' ' login '@' host ':' path]);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmscpout.py	(revision 13101)
@@ -0,0 +1,60 @@
+import socket
+import platform
+import subprocess
+import os
+from MatlabFuncs import *
+
+def issmscpout(host,path,login,port,packages):
+	"""
+	ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpout(host,path,packages)
+	"""
+
+	#get hostname
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#if hostname and host are the same, do a simple copy
+
+	if strcmpi(host,hostname):
+		for package in packages:
+			here=os.getcwd()
+			os.chdir(path)
+			try:
+				os.remove(package)
+			except OSError as e:
+				pass
+			subprocess.call('ln -s %s %s' % (os.path.join(here,package),path),shell=True)
+			os.chdir(here)
+	else:
+		if 'Windows' in platform.system():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmscpout error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s %s:%s' % (ISSM_DIR,username,key,package,host,path),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("issmscpout error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#create string of packages being sent
+			string=''
+			for package in packages:
+				string+=' '+package
+			string+=' '
+		
+			if port:
+				subprocess.call('scp -P %d %s %s@localhost:%s' % (port,string,login,path),shell=True)
+			else:
+				subprocess.call('scp %s %s@%s:%s' % (string,login,host,path),shell=True)
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmssh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmssh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmssh.m	(revision 13101)
@@ -0,0 +1,37 @@
+function issmssh(host,login,port,command)
+%ISSMSSH - wrapper for OS independent ssh command.
+%
+%   usage: 
+%      issmssh(host,command)
+
+%first get hostname 
+hostname=oshostname();
+
+%if same as host, just run the command. 
+if strcmpi(host,hostname),
+	system(command);
+else
+	if ispc,
+		%use the putty project plink.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmssh error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		system([ISSM_DIR '/externalpackages/ssh/plink.exe -ssh -l "' username '" -pw "' key '" ' host ' "' command '"']);
+
+	else
+		%just use standard unix ssh
+		if port,
+			eval(['!ssh -l ' login ' -p ' num2str(port) ' localhost "' command '"']);
+		else
+			eval(['!ssh -l ' login ' ' host ' "' command '"']);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/issmssh.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/issmssh.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/issmssh.py	(revision 13101)
@@ -0,0 +1,42 @@
+import socket
+import platform
+import subprocess
+import os
+from MatlabFuncs import *
+
+def issmssh(host,login,port,command):
+	"""
+	ISSMSSH - wrapper for OS independent ssh command.
+ 
+	   usage: 
+	      issmssh(host,command)
+	"""
+
+	#first get hostname 
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#if same as host, just run the command. 
+	if strcmpi(host,hostname):
+		subprocess.call(command,shell=True)
+	else:
+		if 'Windows' in platform.system():
+			#use the putty project plink.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmssh error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			subprocess.call('%s/externalpackages/ssh/plink.exe -ssh -l "%s" -pw "%s" %s "%s"' % (ISSM_DIR,username,key,host,command),shell=True);
+
+		else:
+			#just use standard unix ssh
+			if port:
+				subprocess.call('ssh -l %s -p %d localhost "%s"' % (login,port,command),shell=True)
+			else:
+				subprocess.call('ssh -l %s %s "%s"' % (login,host,command),shell=True)
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/jplsvn.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/jplsvn.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/jplsvn.m	(revision 13101)
@@ -0,0 +1,15 @@
+function JPL_SVN=jplsvn()
+%ISSMDIR - Get JPL_SVN environment variable
+%
+%   Usage:
+%      JPL_SVN=jplsvn()
+
+if ~ispc,
+	JPL_SVN =getenv('JPL_SVN');
+else
+	JPL_SVN =getenv('JPL_SVN_WIN');
+end
+
+if (isempty(JPL_SVN)),
+	error('jplsvn error message: ''JPL_SVN'' environment variable is empty! You should define JPL_SVN in your .cshrc or .bashrc');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/listfiles.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/listfiles.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/listfiles.m	(revision 13101)
@@ -0,0 +1,22 @@
+function list=listfiles()
+%LISTFILES list files inside a directory
+%        this is very OS dependent.
+%
+%   usage: list=listfiles;
+%
+%
+%   see also LS DIR
+
+%use dir, as it seems to act OS independent
+
+first_list=dir;
+list={};
+
+for i=1:numel(first_list),
+	if (  ~strcmpi(first_list(i).name,'.') &...
+			~strcmpi(first_list(i).name,'..') &...
+			~strcmpi(first_list(i).name,'NightlyRun') &...
+			~strcmpi(first_list(i).name,'.svn')),
+		list{end+1}=first_list(i).name;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/listfilesparallel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/listfilesparallel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/listfilesparallel.m	(revision 13101)
@@ -0,0 +1,15 @@
+function list=listfilesparallel(rank,numprocs)
+%LISTFILESPARALLEL list files inside a directory, depending on rank  and number of processors running this routine.
+%        this is very OS dependent.
+%
+%   usage: list=listfilesparallel(rank,numprocs);
+%
+%
+%   see also LS DIR LISTFILES
+
+list=listfiles';
+numfiles=numel(list);
+
+%we now have a list, split it between all the processors.
+[i1,i2]=parallelrange(rank,numprocs,numfiles);
+list=list(i1:i2);
Index: /issm/branches/trunk-jpl-damage/src/m/os/oshostname.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/oshostname.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/oshostname.m	(revision 13101)
@@ -0,0 +1,22 @@
+function hostname=oshostname()
+%OSHOSTNAME figure out hostname, irrespective of os type
+%
+%   usage: hostname=oshostname();
+%
+%
+
+if ispc,
+	[status,hostname]=system('hostname | sed ''s/-//g''');hostname=hostname(1:end-1);
+
+	if status, 
+		error('oshostname error message: could not run hostname command on windows os');
+	end
+
+else
+	[status,hostname]=system(['hostname -s | sed ''s/-//g''']);
+	if status, 
+		error('oshostname error message: could not run hostname command on *nix os');
+	end
+	hostname=hostname(1:end-1);
+	hostname=ddewhite(hostname);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/os/petscversion.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/petscversion.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/petscversion.m	(revision 13101)
@@ -0,0 +1,26 @@
+function PETSC_VERSION=petscversion()
+%PETSCVERSION - recover petsc version number, inside config.h file
+%
+%   Usage:
+%       PETSC_VERSION=petscversion();
+
+%default
+PETSC_VERSION=3;
+
+configfile=[issmdir() '/config.h'];
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if  strncmp(tline,'#define _PETSC_MAJOR_',21),
+		PETSC_VERSION=str2num(tline(23));
+	end
+end
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/os/petscversion.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/petscversion.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/petscversion.py	(revision 13101)
@@ -0,0 +1,34 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def petscversion():
+	"""
+	PETSCVERSION - recover petsc version number, inside config.h file
+ 
+	   Usage:
+	      PETSC_VERSION=petscversion();
+	"""
+
+	#default
+	PETSC_VERSION=3
+
+	configfile=os.path.join(issmdir(),'config.h')
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOerror("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'#define _PETSC_MAJOR_',21):
+			PETSC_VERSION=int(tline[22])
+			break
+
+	fid.close()
+
+	return PETSC_VERSION
+
Index: /issm/branches/trunk-jpl-damage/src/m/os/recursivepath.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/os/recursivepath.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/os/recursivepath.m	(revision 13101)
@@ -0,0 +1,39 @@
+function p = recursivepath(d)
+%RECURSIVEPATH - generate paths in a directory
+%
+%   this routine is equivalent to Matlab's genpath except that it skips CVS and
+%   .svn directories
+%
+%   Usage:
+%      p = recursivepath(d)
+
+%initialize path to be returned
+p = '';
+sep=pathsep;  %directory separator
+
+% Generate path based on given root directory
+files=dir(d);
+if isempty(files)
+	return
+end
+
+% Add d to the path even if it is empty.
+p = [p d sep];
+
+% set logical vector for subdirectory entries in d
+isdir = logical(cat(1,files.isdir));
+
+% Recursively goes through the subdirectories of d
+dirs=files(isdir); % select only directory entries from the current listing
+for i=1:length(dirs)
+	dirname=dirs(i).name;
+	if ~strcmp(dirname,'.')    & ...
+		~strcmp(dirname,'..')   & ...
+		~strcmp(dirname,'.svn') & ...
+		~strcmp(dirname,'CVS')  & ...
+		~strncmp(dirname,'@',1) & ... %Method directories not allowed in MATLAB path
+		~strcmp(dirname,'private')    %private directories not allowed in MATLAB path
+
+		p = [p recursivepath(fullfile(d,dirname))];
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/contourenvelope.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/contourenvelope.m	(revision 13101)
@@ -0,0 +1,139 @@
+function segments=contourenvelope(md,varargin)
+%CONTOURENVELOPE - build a set of segments enveloping a contour .exp
+%
+%   Usage:
+%      segments=contourenvelope(md,varargin)
+%
+%   Example:
+%      segments=contourenvelope(md,'Stream.exp');
+%      segments=contourenvelope(md,md.mask.elementonfloatingice)
+%      segments=contourenvelope(md);
+
+%some checks
+if nargin>2,
+	help contourenvelope
+	error('contourenvelope error message: bad usage');
+end
+if nargin==2,
+	flags=varargin{1};
+
+	if ischar(flags),
+		file=flags;
+		file=varargin{1};
+		if ~exist(file),
+			error(['contourenvelope error message: file ' file ' not found']);
+		end
+		isfile=1;
+	elseif isnumeric(flags),
+		%do nothing for now
+		isfile=0;
+	else
+		error('contourenvelope error message:  second argument should a file or an elements flag');
+	end
+end
+
+%Now, build the connectivity tables for this mesh.
+%Computing connectivity
+if (size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices & size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices2d),
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if (size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements & size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements2d),
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%get nodes inside profile
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+if md.mesh.dimension==2;
+	mesh.elements=md.mesh.elements;
+	mesh.x=md.mesh.x;
+	mesh.y=md.mesh.y;
+	mesh.numberofvertices=md.mesh.numberofvertices;
+	mesh.numberofelements=md.mesh.numberofelements;
+else
+	mesh.elements=md.mesh.elements2d;
+	mesh.x=md.mesh.x2d;
+	mesh.y=md.mesh.y2d;
+	mesh.numberofvertices=md.mesh.numberofvertices2d;
+	mesh.numberofelements=md.mesh.numberofelements2d;
+end
+
+if nargin==2,
+
+	if isfile,
+		%get flag list of elements and nodes inside the contour
+		nodein=ContourToMesh(mesh.elements,mesh.x,mesh.y,file,'node',1);
+		elemin=(sum(nodein(mesh.elements),2)==size(mesh.elements,2));
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	else
+		%get flag list of elements and nodes inside the contour
+		nodein=zeros(mesh.numberofvertices,1); 
+		elemin=zeros(mesh.numberofelements,1); 
+		
+		pos=find(flags); 
+		elemin(pos)=1;
+		nodein(mesh.elements(pos,:))=1;
+
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	end
+end
+
+%Find element on boundary
+%First: find elements on the boundary of the domain
+flag=mesh.elementconnectivity;
+if nargin==2,
+	flag(find(flag))=elemin(flag(find(flag)));
+end
+elementonboundary=double(prod(flag,2)==0 & sum(flag,2)>0);
+
+%Find segments on boundary
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+for i=1:num_segments,
+	el1=pos(i);
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+	if length(els2)>1,
+		flag=intersect(mesh.elements(els2(1),:),mesh.elements(els2(2),:));
+		nods1=mesh.elements(el1,:);
+		nods1(find(nods1==flag))=[];
+		segments(count,:)=[nods1 el1];
+
+		ord1=find(nods1(1)==mesh.elements(el1,:));
+		ord2=find(nods1(2)==mesh.elements(el1,:));
+
+		%swap segment nodes if necessary
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+	else
+		nods1=mesh.elements(el1,:);
+		flag=setdiff(nods1,mesh.elements(els2,:));
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+				segments(count,:)=[nods el1];
+				ord1=find(nods(1)==mesh.elements(el1,:));
+				ord2=find(nods(2)==mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.m	(revision 13101)
@@ -0,0 +1,58 @@
+function md=parameterize(md,parametername)
+%PARAMETERIZE - parameterize a model
+%
+%   from a parameter matlab file, start filling in all the @model fields that were not 
+%   filled in by the mesh.m and mask.m @model methods.
+%   Warning: the parameter file must be able to be run in Matlab
+%
+%   Usage:
+%      md=parameterize(md,parametername)
+%
+%   Example:
+%      md=parameterize(md,'Square.par');
+
+%some checks
+if ~exist(parametername),
+	error(['parameterize error message: file ' parametername ' not found!']);
+end
+
+%Try and run parameter file.
+temporaryname=['TemporaryParameterFile' num2str(feature('GetPid')) ];
+copyfile(parametername,[temporaryname '.m']);
+
+%WARNING: this is a bug of matlab: the TemporaryParameterFile must be cleared
+%otherwise matlab keeps the previous version of this file which is not what
+%we want!!!
+eval(['clear ' temporaryname]);
+
+try,
+	eval(temporaryname);
+	delete([temporaryname '.m']);
+catch me,
+	delete([temporaryname '.m']);
+
+	%copy error message
+	me2=struct('message',me.message,'stack',me.stack);
+
+	%rename parameter file
+	me2.message=regexprep(me2.message,[temporaryname '.m'],parametername);
+	for i=1:length(me2.stack)-1,
+		me2.stack(i).file=regexprep(me2.stack(i).file,[temporaryname '.m'],parametername);
+		me2.stack(i).name=regexprep(me2.stack(i).name,[temporaryname],parametername);
+		if strcmp(me2.stack(i).name,'parameterize'),
+			%remove error (eval(temporaryname);) misleading
+			me2.stack(i)=[];
+		end
+	end
+
+	%throw error message
+	rethrow(me2);
+end
+
+%Name and notes
+if isempty(md.miscellaneous.name), 
+	[path,root,ext]=fileparts(parametername);
+	md.miscellaneous.name=root; 
+end
+md.miscellaneous.notes=['Model created by using parameter file: ' parametername ' on: ' datestr(now)];
+
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/parameterize.py	(revision 13101)
@@ -0,0 +1,33 @@
+import os
+import datetime
+
+def parameterize(md,parametername):
+	"""
+	PARAMETERIZE - parameterize a model
+
+	   from a parameter python file, start filling in all the model fields that were not 
+	   filled in by the mesh.py and mask.py model methods.
+	   Warning: the parameter file must be able to be run in Python
+
+	   Usage:
+	      md=parameterize(md,parametername)
+
+	   Example:
+	      md=parameterize(md,'Square.par');
+	"""
+
+	#some checks
+	if not os.path.exists(parametername):
+		raise IOError("parameterize error message: file '%s' not found!" % parametername)
+
+	#Try and run parameter file.
+	execfile(parametername)
+
+	#Name and notes
+	if not md.miscellaneous.name:
+		md.miscellaneous.name=os.path.basename(parametername).split('.')[0]
+
+	md.miscellaneous.notes="Model created by using parameter file: '%s' on: %s." % (parametername,datetime.datetime.strftime(datetime.datetime.now(),'%c'))
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.m	(revision 13101)
@@ -0,0 +1,300 @@
+function md=setflowequation(md,varargin)
+%SETELEMENTSTYPE - associate a solution type to each element
+%
+%   This routine works like plotmodel: it works with an even number of inputs
+%   'hutter','macayeal','l1l2','pattyn','stokes' and 'fill' are the possible options
+%   that must be followed by the corresponding exp file or flags list
+%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+%   If user wants every element outside the domain to be 
+%   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+%   an empty string '' will be considered as an empty domain
+%   a string 'all' will be considered as the entire domain
+%   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+%   NB: l1l2 cannot currently be coupled to any other ice flow model
+%
+%   Usage:
+%      md=setflowequation(md,varargin)
+%
+%   Example:
+%      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
+%      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+
+%some checks on list of arguments
+if ((nargin<2) | (nargout~=1)),
+	error('setflowequation error message');
+end
+
+%Process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%Find_out what kind of coupling to use
+coupling_method=getfieldvalue(options,'coupling','tiling');
+if (~strcmpi(coupling_method,'tiling') & ~strcmpi(coupling_method,'penalties')),
+	error('coupling type can only be: tiling or penalties');
+end
+
+%recover elements distribution
+hutterflag   = FlagElements(md,getfieldvalue(options,'hutter',''));
+macayealflag = FlagElements(md,getfieldvalue(options,'macayeal',''));
+pattynflag   = FlagElements(md,getfieldvalue(options,'pattyn',''));
+l1l2flag     = FlagElements(md,getfieldvalue(options,'l1l2',''));
+stokesflag   = FlagElements(md,getfieldvalue(options,'stokes',''));
+filltype     = getfieldvalue(options,'fill','none');
+
+%Flag the elements that have not been flagged as filltype
+if strcmpi(filltype,'hutter'),
+	hutterflag(find(~(macayealflag | pattynflag)))=1;
+elseif strcmpi(filltype,'macayeal'),
+	macayealflag(find(~(hutterflag | pattynflag | stokesflag)))=1;
+elseif strcmpi(filltype,'pattyn'),
+	pattynflag(find(~(hutterflag | macayealflag | stokesflag)))=1;
+end
+
+%check that each element has at least one flag
+if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag==0),
+	error('elements type not assigned, must be specified')
+end
+
+%check that each element has only one flag
+if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag>1),
+	disp('setflowequation warning message: some elements have several types, higher order type is used for them')
+	hutterflag(find(hutterflag & macayealflag))=0;
+	hutterflag(find(hutterflag & pattynflag))=0;
+	macayealflag(find(macayealflag & pattynflag))=0;
+end
+
+%check that l1l2 is not coupled to any other model for now
+if any(l1l2flag) & any(hutterflag | macayealflag | pattynflag | stokesflag)
+	error('l1l2 cannot be coupled to any other model');
+end
+
+%Check that no l1l2 or pattyn or stokes for 2d mesh
+if (md.mesh.dimension==2),
+	if any(l1l2flag | stokesflag | pattynflag)
+		error('stokes and pattyn elements not allowed in 2d mesh, extrude it first')
+	end
+end
+
+%Stokes can only be used alone for now:
+if any(stokesflag) &any(hutterflag),
+	error('stokes cannot be used with any other model for now, put stokes everywhere')
+end
+
+%Initialize node fields
+nodeonhutter=zeros(md.mesh.numberofvertices,1);
+nodeonhutter(md.mesh.elements(find(hutterflag),:))=1;
+nodeonmacayeal=zeros(md.mesh.numberofvertices,1);
+nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+nodeonpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+nodeonl1l2=zeros(md.mesh.numberofvertices,1);
+nodeonl1l2(md.mesh.elements(find(l1l2flag),:))=1;
+nodeonstokes=zeros(md.mesh.numberofvertices,1);
+noneflag=zeros(md.mesh.numberofelements,1);
+
+%First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
+if any(stokesflag),
+	fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+	fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+	stokesflag(find(fullspcelems))=0;
+	nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+end
+
+%Then complete with NoneApproximation or the other model used if there is no stokes
+if any(stokesflag), 
+	if any(pattynflag), %fill with pattyn
+		pattynflag(~stokesflag)=1;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+	elseif any(macayealflag), %fill with macayeal
+		macayealflag(~stokesflag)=1;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+	else %fill with none 
+		noneflag(find(~stokesflag))=1;
+	end
+end
+
+%Now take care of the coupling between MacAyeal and Pattyn
+md.diagnostic.vertex_pairing=[];
+nodeonmacayealpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattynstokes=zeros(md.mesh.numberofvertices,1);
+nodeonmacayealstokes=zeros(md.mesh.numberofvertices,1);
+macayealpattynflag=zeros(md.mesh.numberofelements,1);
+macayealstokesflag=zeros(md.mesh.numberofelements,1);
+pattynstokesflag=zeros(md.mesh.numberofelements,1);
+if strcmpi(coupling_method,'penalties'),
+	%Create the border nodes between Pattyn and MacAyeal and extrude them
+	numnodes2d=md.mesh.numberofvertices2d;
+	numlayers=md.mesh.numberoflayers;
+	bordernodes2d=find(nodeonpattyn(1:numnodes2d) & nodeonmacayeal(1:numnodes2d)); %Nodes connected to two different types of elements
+
+	%initialize and fill in penalties structure
+	if ~isnan(bordernodes2d),
+		penalties=[];
+		for	i=1:numlayers-1,
+			penalties=[penalties; [bordernodes2d bordernodes2d+md.mesh.numberofvertices2d*(i)]];
+		end
+		md.diagnostic.vertex_pairing=penalties;
+	end
+elseif strcmpi(coupling_method,'tiling'),
+	if any(macayealflag) & any(pattynflag), %coupling macayeal pattyn
+		%Find node at the border
+		nodeonmacayealpattyn(find(nodeonmacayeal & nodeonpattyn))=1;
+		%Macayeal elements in contact with this layer become MacAyealPattyn elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealpattyn));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		macayealflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		macayealpattynflag(find(commonelements))=1;
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealpattynflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		macayealflag(pos(pos1))=1;
+		macayealpattynflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		pattynflag(pos(pos2))=1;
+		macayealpattynflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonmacayealpattyn(:)=0;
+		nodeonmacayealpattyn(md.mesh.elements(find(macayealpattynflag),:))=1;
+
+	elseif any(pattynflag) & any(stokesflag), %coupling pattyn stokes
+		%Find node at the border
+		nodeonpattynstokes(find(nodeonpattyn & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become PattynStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonpattynstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		pattynstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(pattynstokesflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonstokes(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:)),2),2);
+		pos1=find(elist==1);
+		stokesflag(pos(pos1))=1;
+		pattynstokesflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		pattynflag(pos(pos2))=1;
+		pattynstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonpattynstokes(:)=0;
+		nodeonpattynstokes(md.mesh.elements(find(pattynstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(macayealflag),
+		%Find node at the border
+		nodeonmacayealstokes(find(nodeonmacayeal & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become MacAyealStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(macayealflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealmacayealelements
+		macayealstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealstokesflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonstokes(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		macayealflag(pos(pos1))=1;
+		macayealstokesflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		stokesflag(pos(pos2))=1;
+		macayealstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonmacayealstokes(:)=0;
+		nodeonmacayealstokes(md.mesh.elements(find(macayealstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(hutterflag),
+		error('type of coupling not supported yet');
+	end
+end
+
+%Create MacaAyealPattynApproximation where needed
+md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
+md.flowequation.element_equation(find(noneflag))=0;
+md.flowequation.element_equation(find(hutterflag))=1;
+md.flowequation.element_equation(find(macayealflag))=2;
+md.flowequation.element_equation(find(l1l2flag))=8;
+md.flowequation.element_equation(find(pattynflag))=3;
+md.flowequation.element_equation(find(stokesflag))=4;
+md.flowequation.element_equation(find(macayealpattynflag))=5;
+md.flowequation.element_equation(find(macayealstokesflag))=6;
+md.flowequation.element_equation(find(pattynstokesflag))=7;
+
+%border
+md.flowequation.borderpattyn=nodeonpattyn;
+md.flowequation.bordermacayeal=nodeonmacayeal;
+md.flowequation.borderstokes=nodeonstokes;
+
+%Create vertices_type
+md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
+pos=find(nodeonmacayeal);
+md.flowequation.vertex_equation(pos)=2;
+pos=find(nodeonl1l2);
+md.flowequation.vertex_equation(pos)=8;
+pos=find(nodeonpattyn);
+md.flowequation.vertex_equation(pos)=3;
+pos=find(nodeonhutter);
+md.flowequation.vertex_equation(pos)=1;
+pos=find(nodeonmacayealpattyn);
+md.flowequation.vertex_equation(pos)=5;
+pos=find(nodeonstokes);
+md.flowequation.vertex_equation(pos)=4;
+if any(stokesflag),
+	pos=find(~nodeonstokes);
+	if(~any(pattynflag) & ~any(macayealflag)),
+		md.flowequation.vertex_equation(pos)=0;
+	end
+end
+pos=find(nodeonpattynstokes);
+md.flowequation.vertex_equation(pos)=7;
+pos=find(nodeonmacayealstokes);
+md.flowequation.vertex_equation(pos)=6;
+
+%figure out solution types
+md.flowequation.ishutter=double(any(md.flowequation.element_equation==1));
+md.flowequation.ismacayealpattyn=double(any(md.flowequation.element_equation==2 | md.flowequation.element_equation==3));
+md.flowequation.isstokes=double(any(md.flowequation.element_equation==4));
+md.flowequation.isl1l2=double(any(md.flowequation.element_equation==8));
+
+return
+
+%Check that tiling can work:
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderstokes) & any(md.flowequation.borderstokes + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.borderstokes) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.borderstokes~=1),
+	error('error coupling domain too irregular');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/setflowequation.py	(revision 13101)
@@ -0,0 +1,291 @@
+import numpy
+from model import *
+from pairoptions import *
+from MatlabFuncs import *
+from FlagElements import *
+
+def setflowequation(md,*args):
+	"""
+	SETELEMENTSTYPE - associate a solution type to each element
+
+	   This routine works like plotmodel: it works with an even number of inputs
+	   'hutter','macayeal','pattyn','l1l2','stokes' and 'fill' are the possible options
+	   that must be followed by the corresponding exp file or flags list
+	   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+	   If user wants every element outside the domain to be 
+	   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+	   an empty string '' will be considered as an empty domain
+	   a string 'all' will be considered as the entire domain
+	   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+
+	   Usage:
+	      md=setflowequation(md,varargin)
+
+	   Example:
+	      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
+	      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+	"""
+
+	#some checks on list of arguments
+	if not isinstance(md,model) or not len(args):
+		raise TypeError("setflowequation error message")
+
+	#process options
+	options=pairoptions(*args)
+#	options=deleteduplicates(options,1);
+
+	#Find_out what kind of coupling to use
+	coupling_method=options.getfieldvalue('coupling','tiling')
+	if not strcmpi(coupling_method,'tiling') and not strcmpi(coupling_method,'penalties'):
+		raise TypeError("coupling type can only be: tiling or penalties")
+
+	#recover elements distribution
+	hutterflag   = FlagElements(md,options.getfieldvalue('hutter',''))
+	macayealflag = FlagElements(md,options.getfieldvalue('macayeal',''))
+	pattynflag   = FlagElements(md,options.getfieldvalue('pattyn',''))
+	l1l2flag     = FlagElements(md,options.getfieldvalue('l1l2',''))
+	stokesflag   = FlagElements(md,options.getfieldvalue('stokes',''))
+	filltype     = options.getfieldvalue('fill','none')
+
+	#Flag the elements that have not been flagged as filltype
+	if   strcmpi(filltype,'hutter'):
+		hutterflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(macayealflag,pattynflag)))]=1
+	elif strcmpi(filltype,'macayeal'):
+		macayealflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(hutterflag,numpy.logical_or(pattynflag,stokesflag))))]=1
+	elif strcmpi(filltype,'pattyn'):
+		pattynflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(hutterflag,numpy.logical_or(macayealflag,stokesflag))))]=1
+
+	#check that each element has at least one flag
+	if not any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag):
+		raise TypeError("elements type not assigned, must be specified")
+
+	#check that each element has only one flag
+	if any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag>1):
+		print "setflowequation warning message: some elements have several types, higher order type is used for them"
+		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,macayealflag))]=0
+		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,pattynflag))]=0
+		macayealflag[numpy.nonzero(numpy.logical_and(macayealflag,pattynflag))]=0
+
+	#Check that no pattyn or stokes for 2d mesh
+	if md.mesh.dimension==2:
+		if numpy.any(numpy.logical_or(l1l2flag,stokesflag,pattynflag)):
+			raise TypeError("stokes and pattyn elements not allowed in 2d mesh, extrude it first")
+
+	#Stokes can only be used alone for now:
+	if any(stokesflag) and any(hutterflag):
+		raise TypeError("stokes cannot be used with any other model for now, put stokes everywhere")
+
+	#Initialize node fields
+	nodeonhutter=numpy.zeros(md.mesh.numberofvertices)
+	nodeonhutter[md.mesh.elements[numpy.nonzero(hutterflag),:].astype(int)-1]=1
+	nodeonmacayeal=numpy.zeros(md.mesh.numberofvertices)
+	nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+	nodeonl1l2=numpy.zeros(md.mesh.numberofvertices)
+	nodeonl1l2[md.mesh.elements[numpy.nonzero(l1l2flag),:].astype(int)-1]=1
+	nodeonpattyn=numpy.zeros(md.mesh.numberofvertices)
+	nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+	nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+	noneflag=numpy.zeros(md.mesh.numberofelements)
+
+	#First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
+	if any(stokesflag):
+#		fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+		fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx))+ \
+		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvy))+ \
+		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvz))==3, \
+		                              numpy.logical_and(nodeonpattyn,nodeonstokes)).astype(int)    #find all the nodes on the boundary of the domain without icefront
+#		fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+		fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements.astype(int)-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
+		stokesflag[numpy.nonzero(fullspcelems)]=0
+		nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+	#Then complete with NoneApproximation or the other model used if there is no stokes
+	if any(stokesflag): 
+		if   any(pattynflag):    #fill with pattyn
+			pattynflag[numpy.logical_not(stokesflag)]=1
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+		elif any(macayealflag):    #fill with macayeal
+			macayealflag[numpy.logical_not(stokesflag)]=1
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+		else:    #fill with none 
+			noneflag[numpy.nonzero(numpy.logical_not(stokesflag))]=1
+
+	#Now take care of the coupling between MacAyeal and Pattyn
+	md.diagnostic.vertex_pairing=numpy.array([])
+	nodeonmacayealpattyn=numpy.zeros(md.mesh.numberofvertices)
+	nodeonpattynstokes=numpy.zeros(md.mesh.numberofvertices)
+	nodeonmacayealstokes=numpy.zeros(md.mesh.numberofvertices)
+	macayealpattynflag=numpy.zeros(md.mesh.numberofelements)
+	macayealstokesflag=numpy.zeros(md.mesh.numberofelements)
+	pattynstokesflag=numpy.zeros(md.mesh.numberofelements)
+	if   strcmpi(coupling_method,'penalties'):
+		#Create the border nodes between Pattyn and MacAyeal and extrude them
+		numnodes2d=md.mesh.numberofvertices2d
+		numlayers=md.mesh.numberoflayers
+		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[1:numnodes2d],nodeonmacayeal[1:numnodes2d]))    #Nodes connected to two different types of elements
+
+		#initialize and fill in penalties structure
+		if numpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):
+			penalties=numpy.zeros((0,2))
+			for	i in xrange(1,numlayers):
+				penalties=numpy.concatenate((penalties,numpy.concatenate((bordernodes2d,bordernodes2d+md.mesh.numberofvertices2d*(i)),axis=1)),axis=0)
+			md.diagnostic.vertex_pairing=penalties
+
+	elif strcmpi(coupling_method,'tiling'):
+		if   any(macayealflag) and any(pattynflag):    #coupling macayeal pattyn
+			#Find node at the border
+			nodeonmacayealpattyn[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonpattyn))]=1
+			#Macayeal elements in contact with this layer become MacAyealPattyn elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealpattyn))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
+			macayealflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealpattynelements
+			macayealpattynflag[numpy.nonzero(commonelements)]=1
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(macayealpattynflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
+			pos1=[i for i,item in enumerate(elist) if item==1]
+			macayealflag[pos[pos1]]=1
+			macayealpattynflag[pos[pos1]]=0
+			pos2=[i for i,item in enumerate(elist) if item==-1]
+			pattynflag[pos[pos2]]=1
+			macayealpattynflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+			nodeonpattyn[:]=0
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+			nodeonmacayealpattyn[:]=0
+			nodeonmacayealpattyn[md.mesh.elements[numpy.nonzero(macayealpattynflag),:].astype(int)-1]=1
+
+		elif any(pattynflag) and any(stokesflag):    #coupling pattyn stokes
+			#Find node at the border
+			nodeonpattynstokes[numpy.nonzero(numpy.logical_and(nodeonpattyn,nodeonstokes))]=1
+			#Stokes elements in contact with this layer become PattynStokes elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonpattynstokes))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
+			stokesflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealpattynelements
+			pattynstokesflag[numpy.nonzero(commonelements)]=1
+			nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(pattynstokesflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			pos1=[i for i,item in enumerate(elist) if item==1]
+			stokesflag[pos[pos1]]=1
+			pattynstokesflag[pos[pos1]]=0
+			pos2=[i for i,item in enumerate(elist) if item==-1]
+			pattynflag[pos[pos2]]=1
+			pattynstokesflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonstokes[:]=0
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+			nodeonpattyn[:]=0
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+			nodeonpattynstokes[:]=0
+			nodeonpattynstokes[md.mesh.elements[numpy.nonzero(pattynstokesflag),:].astype(int)-1]=1
+
+		elif any(stokesflag) and any(macayealflag):
+			#Find node at the border
+			nodeonmacayealstokes[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonstokes))]=1
+			#Stokes elements in contact with this layer become MacAyealStokes elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealstokes))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(macayealflag)]=0    #only one layer: the elements previously in macayeal
+			stokesflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealmacayealelements
+			macayealstokesflag[numpy.nonzero(commonelements)]=1
+			nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(macayealstokesflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
+			pos1=[i for i,item in enumerate(elist) if item==1]
+			macayealflag[pos[pos1]]=1
+			macayealstokesflag[pos[pos1]]=0
+			pos2=[i for i,item in enumerate(elist) if item==-1]
+			stokesflag[pos[pos2]]=1
+			macayealstokesflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+			nodeonstokes[:]=0
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+			nodeonmacayealstokes[:]=0
+			nodeonmacayealstokes[md.mesh.elements[numpy.nonzero(macayealstokesflag),:].astype(int)-1]=1
+
+		elif any(stokesflag) and any(hutterflag):
+			raise TypeError("type of coupling not supported yet")
+
+	#Create MacaAyealPattynApproximation where needed
+	md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements)
+	md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
+	md.flowequation.element_equation[numpy.nonzero(hutterflag)]=1
+	md.flowequation.element_equation[numpy.nonzero(macayealflag)]=2
+	md.flowequation.element_equation[numpy.nonzero(l1l2flag)]=8
+	md.flowequation.element_equation[numpy.nonzero(pattynflag)]=3
+	md.flowequation.element_equation[numpy.nonzero(stokesflag)]=4
+	md.flowequation.element_equation[numpy.nonzero(macayealpattynflag)]=5
+	md.flowequation.element_equation[numpy.nonzero(macayealstokesflag)]=6
+	md.flowequation.element_equation[numpy.nonzero(pattynstokesflag)]=7
+
+	#border
+	md.flowequation.borderpattyn=nodeonpattyn
+	md.flowequation.bordermacayeal=nodeonmacayeal
+	md.flowequation.borderstokes=nodeonstokes
+
+	#Create vertices_type
+	md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices)
+	pos=numpy.nonzero(nodeonmacayeal)
+	md.flowequation.vertex_equation[pos]=2
+	pos=numpy.nonzero(nodeonl1l2)
+	md.flowequation.vertex_equation[pos]=8
+	pos=numpy.nonzero(nodeonpattyn)
+	md.flowequation.vertex_equation[pos]=3
+	pos=numpy.nonzero(nodeonhutter)
+	md.flowequation.vertex_equation[pos]=1
+	pos=numpy.nonzero(nodeonmacayealpattyn)
+	md.flowequation.vertex_equation[pos]=5
+	pos=numpy.nonzero(nodeonstokes)
+	md.flowequation.vertex_equation[pos]=4
+	if any(stokesflag):
+		pos=numpy.nonzero(numpy.logical_not(nodeonstokes))
+		if not (any(pattynflag) or any(macayealflag)):
+			md.flowequation.vertex_equation[pos]=0
+	pos=numpy.nonzero(nodeonpattynstokes)
+	md.flowequation.vertex_equation[pos]=7
+	pos=numpy.nonzero(nodeonmacayealstokes)
+	md.flowequation.vertex_equation[pos]=6
+
+	#figure out solution types
+	md.flowequation.ishutter=float(any(md.flowequation.element_equation==1))
+	md.flowequation.ismacayealpattyn=float(numpy.any(numpy.logical_or(md.flowequation.element_equation==2,md.flowequation.element_equation==3)))
+	md.flowequation.isl1l2=float(any(md.flowequation.element_equation==8))
+	md.flowequation.isstokes=float(any(md.flowequation.element_equation==4))
+
+	return md
+
+	#Check that tiling can work:
+	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderstokes) and any(md.flowequation.borderstokes + md.flowequation.bordermacayeal !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.borderstokes) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.borderstokes !=1):
+		raise TypeError("error coupling domain too irregular")
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.m	(revision 13101)
@@ -0,0 +1,49 @@
+function md=setmask(md,floatingicename,groundedicename)
+%SETMASK - establish boundaries between grounded and floating ice.
+%
+%   By default, ice is considered grounded. The contour floatingicename defines nodes 
+%   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+%   that are grounded (ie: ice rises, islands, etc ...)
+%   All input files are in the Argus format (extension .exp).
+%
+%   Usage:
+%      md=setmask(md,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask(md,'all','');
+%      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+%some checks on list of arguments
+if ((nargin~=3) | (nargout~=1)),
+	help mask
+	error('mask error message');
+end
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+
+%the order here is important. we choose vertexongroundedice as default on the grounding line.
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+vertexonfloatingice(find(~vertexongroundedice))=1;
+%}}}
+
+%Return: 
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementongroundedice=elementongroundedice;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mask.elementonwater=zeros(md.mesh.numberofelements,1);
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask.py	(revision 13101)
@@ -0,0 +1,55 @@
+from numpy import *
+import FlagElements as fe
+
+def setmask(md, floatingicename, groundedicename):
+	#SETMASK - establish boundaries between grounded and floating ice.
+	#
+	#   By default, ice is considered grounded. The contour floatingicename defines nodes 
+	#   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+	#   that are grounded (ie: ice rises, islands, etc ...)
+	#   All input files are in the Argus format (extension .exp).
+	#
+	#   Usage:
+	#      md=setmask(md,floatingicename,groundedicename)
+	#
+	#   Examples:
+	#      md=setmask(md,'all','');
+	#      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+	#%Get assigned fields
+	x = md.mesh.x
+	y = md.mesh.y
+	elements = md.mesh.elements
+
+	#Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
+	elementonfloatingice = fe.FlagElements(md, floatingicename)
+	elementongroundedice = fe.FlagElements(md, groundedicename) 
+
+	#Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+	#arrays come from domain outlines that can intersect one another: 
+
+	elementonfloatingice = logical_and(elementonfloatingice,~elementongroundedice)
+	elementongroundedice = ~elementonfloatingice
+
+	#the order here is important. we choose vertexongroundedice as default on the grounding line.
+	vertexonfloatingice = zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice = zeros(md.mesh.numberofvertices,'bool')
+
+	pos=argwhere(elementongroundedice==1)
+	pos=md.mesh.elements[pos,:]-1
+	if pos.size:
+		vertexongroundedice[pos]=True
+
+	pos=argwhere(~vertexongroundedice)
+	if pos.size:
+		vertexonfloatingice[pos]=True;
+	#%}}}
+
+	#Return: 
+	md.mask.elementonfloatingice = double(elementonfloatingice)
+	md.mask.vertexonfloatingice = double(vertexonfloatingice)
+	md.mask.elementongroundedice = double(elementongroundedice)
+	md.mask.vertexongroundedice = double(vertexongroundedice)
+	md.mask.vertexonwater = zeros(md.mesh.numberofvertices)
+	md.mask.elementonwater = zeros(md.mesh.numberofelements)
+	return md
Index: /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask2.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask2.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/parameterization/setmask2.m	(revision 13101)
@@ -0,0 +1,148 @@
+function md=setmask2(md,landname,floatingicename,groundedicename)
+%GEOGRAPHY2 - establish land, ice sheet and ice shelf areas in a domains.
+%
+%   Usage:
+%      md=setmask2(md,landname,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask2(md,'LandName.exp','Iceshelves.exp','Islands.exp');
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%recover elements and nodes on land.
+if ischar(landname),
+	[vertexonland,elementonland]=ContourToMesh(elements,x,y,landname,'element and node',2);
+elseif isfloat(landname),
+	if size(landname,1)~=md.mesh.numberofelements,
+		error('Landname for area must be of same size as number of elements in model');
+	end
+	elementonland=landname;
+	vertexonland=zeros(md.mesh.numberofvertices,1);
+	vertexonland(md.mesh.elements(find(elementonland),:))=1;
+else
+	error('Invalid area option option');
+end
+
+%Now, build the connectivity tables for this mesh.
+if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%any element with 3 nodes on land should be on land:
+elementsonwater=find(~elementonland);
+wrongelements=elementsonwater(find(( vertexonland(md.mesh.elements(elementsonwater,1)) + vertexonland(md.mesh.elements(elementsonwater,2)) + vertexonland(md.mesh.elements(elementsonwater,3)) ...
+                  )==3));
+elementonland(wrongelements)=1;
+
+%any element with its barycentre on land should be on land: (only if landname is an expfile)
+if ischar(landname),
+weights={[1;1;1],[2;1;1],[1;2;1],[1;1;2]};
+	for i=1:length(weights),
+		xelem=x(md.mesh.elements)*weights{i}/sum(weights{i});
+		yelem=y(md.mesh.elements)*weights{i}/sum(weights{i});
+	end
+	baryonland=ContourToNodes(xelem,yelem,landname,1);
+	pos=find(~baryonland); elementonland(pos)=0;
+	pos=find(baryonland); elementonland(pos)=1;
+end
+
+%figure out which elements on land are actually in the middle of the ocean!
+pos1=find(elementonland); 
+connectedtoland=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtoland); connectedtoland(pos)=1-elementonland(connectedtoland(pos));
+connectedtolandsum=sum(connectedtoland,2);
+waterelements=pos1(find(connectedtolandsum==3));
+elementonland(waterelements)=0;
+
+%figure out which elements on water  are actually in the middle of the land!
+pos1=find(~elementonland); 
+connectedtowater=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtowater); connectedtowater(pos)=elementonland(connectedtowater(pos));
+connectedtowatersum=sum(connectedtowater,2);
+landelements=pos1(find(connectedtowatersum==3));
+elementonland(landelements)=1;
+
+%recover arrays of ice shelf nodes and elements, and ice sheet nodes and elements.
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+vertexonfloatingice(md.mesh.elements(find(elementonfloatingice),:))=1;
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+
+%now correct, so that none of the floatingice and groundedice elements and nodes are in the water.
+pos=find(~elementonland);
+elementonfloatingice(pos)=0; 
+elementongroundedice(pos)=0;
+
+pos=find(~vertexonland);
+vertexonfloatingice(pos)=0; 
+vertexongroundedice(pos)=0;
+
+%create vertexonwater and elementonwater: 
+vertexonwater=double(~vertexonland);
+elementonwater=double(~elementonland);
+
+%correct for islands:
+vertexonfloatingice=double(vertexonfloatingice & ~vertexongroundedice);
+elementonfloatingice=double(elementonfloatingice & ~elementongroundedice);
+
+%now, groundedices are everything except iceshelves and water
+vertexongroundedice=double(~vertexonfloatingice & ~vertexonwater);
+elementongroundedice=double(~elementonfloatingice & ~elementonwater);
+
+%Deal with segments on neumann:
+
+%Get current connectivity
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+
+%put 0 for elements on water
+pos=find(mesh.elementconnectivity);
+mesh.elementconnectivity(pos)=mesh.elementconnectivity(pos).*(~elementonwater(mesh.elementconnectivity(pos)));
+
+%put line of ones for elements on water
+pos=find(elementonwater);
+mesh.elementconnectivity(pos,:)=1;% line of ones for elements on water so they won't be considered
+
+%resort lines (zeros must be at the last column for findsegments)
+mesh.elementconnectivity=sort(mesh.elementconnectivity,2,'descend');
+
+%call findsegments to build segment using THIS conectivity
+md.mesh.segments=findsegments(md,'mesh.elementconnectivity',mesh.elementconnectivity);
+
+%some final checks: 
+%check that no node thinks it's on an ice shelf or ice sheet, and lies actually in the middle of the water.
+nodesgrounded=find(~vertexonwater);
+lengthconnectivity=size(md.mesh.vertexconnectivity,2);
+groundedcounters=md.mesh.vertexconnectivity(nodesgrounded,lengthconnectivity);
+groundedconnectivity=md.mesh.vertexconnectivity(nodesgrounded,1:lengthconnectivity-1);
+pos=find(groundedconnectivity);
+groundedconnectivity(pos)=elementonwater(groundedconnectivity(pos));
+groundedsum=sum(groundedconnectivity,2);
+errorflags=find(groundedsum==groundedcounters);
+errornodes=nodesgrounded(errorflags);
+
+vertexonwater(errornodes)=1;
+vertexongroundedice(errornodes)=0;
+vertexonfloatingice(errornodes)=0;
+
+%Return: 
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonwater=vertexonwater;
+md.mask.elementonwater=elementonwater;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.elementongroundedice=elementongroundedice;
+
+md.mesh.segmentmarkers(:)=1;
Index: /issm/branches/trunk-jpl-damage/src/m/partition/AreaAverageOntoPartition.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/partition/AreaAverageOntoPartition.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/partition/AreaAverageOntoPartition.m	(revision 13101)
@@ -0,0 +1,55 @@
+function partvector=AreaAverageOntoPartition(md,vector,layer)
+%AREAAVERAGEONTOPARTITION 
+%   compute partition values for a certain vector expressed on the vertices of the mesh.
+%   Use area weighted average.
+%
+%   Usage:
+%      average=AreaAverageOntoPartition(md,vector)
+%      average=AreaAverageOntoPartition(md,vector,layer) %if in 3D, chose which layer is partitioned
+
+%some checks
+if md.mesh.dimension==3,
+	if nargin~=3,
+		error('layer should be provided onto which Area Averaging occurs');
+	end
+	%save 3D model
+	md3d=md;
+	
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+
+	%run connectivity routine
+	md=adjacency(md);
+
+	%finally, project vector: 
+	vector=project2d(md3d,vector,layer);
+	md.qmu.partition=project2d(md3d,md3d.qmu.partition,layer);
+end
+
+%ok, first check that part is Matlab indexed
+part=md.qmu.partition+1;
+
+%some check: 
+if md.qmu.numberofpartitions~=max(part),
+	error('AreaAverageOntoPartition error message: ''npart'' should be equal to max(md.qmu.partition)');
+end
+
+%initialize output
+partvector=zeros(max(part),1);
+
+%start weight average
+weightedvector=vector.*md.qmu.vertex_weight;
+for i=1:max(part),
+	pos=find(part==i);
+	partvector(i)=sum(weightedvector(pos))/sum(md.qmu.vertex_weight(pos));
+end
+
+%in 3D, restore 3D model:
+if md.mesh.dimension==3,
+	md=md3d;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/partition/adjacency.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/partition/adjacency.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/partition/adjacency.m	(revision 13101)
@@ -0,0 +1,26 @@
+function md=adjacency(md);
+%ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
+%
+%  function to create the adjacency matrix from the connectivity table.
+%
+%  the required output is:
+%    md.adj_mat     (double [sparse nv x nv], vertex adjacency matrix)
+%    md.qmu.vertex_weight        (double [nv], vertex weights)
+
+indi=[md.mesh.elements(:,1);md.mesh.elements(:,2);md.mesh.elements(:,3)];
+indj=[md.mesh.elements(:,2);md.mesh.elements(:,3);md.mesh.elements(:,1)];
+values=1;
+
+md.qmu.adjacency=sparse(indi,indj,values,md.mesh.numberofvertices,md.mesh.numberofvertices);
+md.qmu.adjacency=double([md.qmu.adjacency | md.qmu.adjacency']);
+
+%now, build vwgt:
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%get node connectivity
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+
+connectivity=md.mesh.vertexconnectivity(:,1:end-1);
+pos=find(connectivity);
+connectivity(pos)=areas(connectivity(pos))/3;
+md.qmu.vertex_weight=sum(connectivity,2);
Index: /issm/branches/trunk-jpl-damage/src/m/partition/flagedges.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/partition/flagedges.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/partition/flagedges.m	(revision 13101)
@@ -0,0 +1,45 @@
+function [xsegments ysegments]=flagedges(elements,x,y,partition);
+%FLAGEDGES - return pairs of x,y segments, delimiting partitions.
+%
+%   Usage:
+%      [xsegments ysegments]=flagedges(elements,x,y,partition)
+
+xsegments=[];
+ysegments=[];
+
+for i=1:size(elements,1),
+	m1=partition(elements(i,1));
+	m2=partition(elements(i,2));
+	m3=partition(elements(i,3));
+	x1=x(elements(i,1));
+	x2=x(elements(i,2));
+	x3=x(elements(i,3));
+	y1=y(elements(i,1));
+	y2=y(elements(i,2));
+	y3=y(elements(i,3));
+
+	if (m1~=m2) & (m1~=m3) & (m2~=m3),
+		xmiddle=(x1+x2+x3)/3;
+		ymiddle=(y1+y2+y3)/3;
+		xsegments=[xsegments; (x1+x2)/2 xmiddle];
+		xsegments=[xsegments; (x1+x3)/2 xmiddle];
+		xsegments=[xsegments; (x2+x3)/2 xmiddle];
+		ysegments=[ysegments; (y1+y2)/2 ymiddle];
+		ysegments=[ysegments; (y1+y3)/2 ymiddle];
+		ysegments=[ysegments; (y2+y3)/2 ymiddle];
+	end
+
+	if (m1==m2) & (m1~=m3),
+		xsegments=[xsegments; (x1+x3)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y3)/2 (y2+y3)/2];
+	end
+	if (m1==m3) & (m2~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y2+y3)/2];
+	end
+
+	if (m2==m3) & (m1~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x1+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y1+y3)/2];
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/partition/partitioner.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/partition/partitioner.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/partition/partitioner.m	(revision 13101)
@@ -0,0 +1,107 @@
+function md=partitioner(md,varargin)
+%PARTITIONER - partition mesh 
+%
+%   List of options to partitioner: 
+%
+%   package: 'chaco', 'metis' or 'scotch'
+%   npart: number of partitions.
+%   weighting: 'on' or 'off': default off
+%   section:  1 by defaults(1=bisection, 2=quadrisection, 3=octasection)
+%   recomputeadjacency:  'on' by default (set to 'off' to compute existing one)
+%   Output: md.qmu.partition recover the partition vector
+%   
+%   Usage:
+%      md=partitioner(md,'package','chaco','npart',100,'weighting','on');
+%
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'package','chaco');
+options=addfielddefault(options,'npart',10);
+options=addfielddefault(options,'weighting','on');
+options=addfielddefault(options,'section',1);
+options=addfielddefault(options,'recomputeadjacency','on');
+
+%get package: 
+package=getfieldvalue(options,'package');
+npart=getfieldvalue(options,'npart');
+recomputeadjacency=getfieldvalue(options,'recomputeadjacency');
+
+if(md.mesh.dimension==3),
+	%partitioning essentially happens in 2D. So partition in 2D, then 
+	%extrude the partition vector vertically. 
+	md3d=md; %save  for later
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+end
+
+%adjacency matrix if needed:
+if strcmpi(recomputeadjacency,'on'),
+	md=adjacency(md);
+else
+	disp('skipping adjacency matrix computation as requested in the options');
+end
+
+
+if strcmpi(package,'chaco'),
+
+	%  default method (from chaco.m)
+	method=[1 1 0 0 1 1 50 0 .001 7654321]';
+	method(1)=3;    %  global method (3=inertial (geometric))
+	method(3)=0;    %  vertex weights (0=off, 1=on)
+	
+	%specify bisection
+	method(6)=getfieldvalue(options,'section');%  ndims (1=bisection, 2=quadrisection, 3=octasection)
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+		method(3)=1;
+	else 
+		weights=[];
+	end
+	
+	%  partition into nparts
+	part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y ,md.mesh.z,method,npart,[])'+1; %index partitions from 1 up. like metis.
+
+elseif strcmpi(package,'scotch'),
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+	end
+	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
+	
+	part=maptab(:,2);%index partitions from 1 up. like metis.
+
+
+elseif strcmpi(package,'linear'),
+
+	part=1:1:md.mesh.numberofvertices;
+
+elseif strcmpi(package,'metis'),
+
+	[element_partitioning,part]=MeshPartition(md.mesh,md.qmu.numberofpartitions);
+
+else
+
+	error(['partitioner error message: could not find ' package ' partitioner']);
+	help partitioner
+end
+
+%extrude if we are in 3D:
+if md.mesh.dimension==3,
+	md3d.qmu.vertex_weight=md.qmu.vertex_weight;
+	md3d.qmu.adjacency=md.qmu.adjacency;
+	md=md3d;
+	part=project3d(md,'vector',part','type','node');
+end
+
+md.qmu.partition=part;
Index: /issm/branches/trunk-jpl-damage/src/m/plot/applyoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/applyoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/applyoptions.m	(revision 13101)
@@ -0,0 +1,509 @@
+function applyoptions(md,data,options)
+%APPLYOPTIONS - apply the options to current plot
+%
+%   Usage:
+%      applyoptions(md,data,options)
+%
+%   See also: PLOTMODEL, PARSE_OPTIONS
+		
+
+%some defaults
+if isfield(md.mesh,'hemisphere'),
+	if strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
+	elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
+	end
+end
+
+%fontsize
+fontsize=getfieldvalue(options,'fontsize',14);
+
+%fontweight
+fontweight=getfieldvalue(options,'fontweight','normal');
+
+%title
+if exist(options,'title')
+	titlevalue=getfieldvalue(options,'title');
+	if iscell(titlevalue),
+		title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+	else
+		if ~isnan(titlevalue),
+			title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+		end
+	end
+end
+
+%xlabel, ylabel and zlabel
+if exist(options,'xlabel');
+	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'ylabel');
+	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'zlabel');
+	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%xticks, yticks and zticks
+if exist(options,'xtick'), set(gca,'XTick',getfieldvalue(options,'xtick')); end
+if exist(options,'ytick'), set(gca,'YTick',getfieldvalue(options,'ytick')); end
+if exist(options,'ztick'), set(gca,'ZTick',getfieldvalue(options,'ztick')); end
+
+%view 
+if md.mesh.dimension==3 & ~exist(options,'layer'),
+	view(getfieldvalue(options,'view',3));
+else
+	view(getfieldvalue(options,'view',2));
+end
+
+%axis
+set(gca,'FontSize',getfieldvalue(options,'axisfontsize',fontsize));;
+if exist(options,'axis')
+	eval(['axis ' getfieldvalue(options,'axis')]);
+else
+	if ((md.mesh.dimension==2) | exist(options,'layer')),
+		axis tight equal;
+	else
+		axis auto tight
+	end
+end
+
+%box
+if exist(options,'box')
+	eval(['box ' getfieldvalue(options,'box')]);
+end
+
+%xlim, ylim and zlim
+if exist(options,'xlim');
+	xlim(getfieldvalue(options,'xlim'));
+end
+if exist(options,'ylim');
+	ylim(getfieldvalue(options,'ylim'));
+end
+if exist(options,'zlim');
+	zlim(getfieldvalue(options,'zlim'));
+end
+
+%latlon
+%Must be done here (before xlim and ylim??) so that it uses the same xlim and ylim as plot_overlay
+%these are changed by axis that follows
+if ~strcmpi(getfieldvalue(options,'latlon','off'),'off')
+	latlonoverlay(md,options);
+end
+
+%Basinzoom
+if exist(options,'basin');
+	basinzoom(options);
+end
+
+%ShowBasins
+if strcmpi(getfieldvalue(options,'showbasins','off'),'on')
+	showbasins(options);
+end
+
+%Caxis
+if exist(options,'caxis'),
+	caxis(getfieldvalue(options,'caxis'));
+end
+
+%shading
+if exist(options,'shading'),
+	shading(getfieldvalue(options,'shading'));
+end
+
+%grid
+if exist(options,'grid'),
+	if strcmpi(getfieldvalue(options,'grid'),'on'),
+		grid on;
+	end
+end
+
+%colormap
+c = getcolormap(options);
+h = colormap(c);
+
+%wrapping
+if exist(options,'wrapping'),
+	if ~exist(options,'colormap'),
+		h=jet;
+	end
+	colormap(repmat(h,getfieldvalue(options,'wrapping',1),1));
+end
+
+%colorbar
+if getfieldvalue(options,'colorbar',1)==1,
+	if exist(options,'colorbarcornerposition'),
+		c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
+	else 
+		c=colorbar('peer',gca);
+	end
+	set(c,'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'YColor',getfieldvalue(options,'FontColor','k'));
+	if exist(options,'wrapping')
+		lim=get(c,'Ylim');
+		lim=[lim(1) lim(1)+(lim(2)-lim(1))/getfieldvalue(options,'wrapping')];
+		set(c,'Ylim',lim);
+	end
+	if exist(options,'colorbarpos'),
+		set(c,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	if exist(options,'log'),
+		nlab=5;
+		logvalue=getfieldvalue(options,'log');
+
+		scaleminmax=caxis;
+		Min=min(scaleminmax);
+		Max=max(scaleminmax);
+		set(c,'YLim',[Min Max]); % set colorbar limits
+		set(c,'YTick',linspace(Min,Max,nlab));     % set tick mark locations
+
+		labels = cell(1,nlab);
+		tick_vals = linspace(Min,Max,nlab);
+		tick_vals = exp(log(logvalue)*tick_vals);
+		warning off MATLAB:log:logOfZero;
+		for i = 1:nlab
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+			%labels{i} = sprintf('%-.4g',round_ice(tick_vals(i),2));
+		end
+		warning on MATLAB:log:logOfZero;
+		set(c,'YTickLabel',labels);
+	end 
+ 	if exist(options,'cbYLim'); 
+		set(c,'YLim',getfieldvalue(options,'cbYLim'));
+	end
+	if exist(options,'colorbartitle'),
+		set(get(c,'title'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbartitle'),...
+			'Color',getfieldvalue(options,'FontColor','k'));
+	end
+	if exist(options,'colorbarYLabel'),
+		set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
+			'Color',getfieldvalue(options,'FontColor','k'),'Interpreter',getfieldvalue(options,'Interpreter','none'));
+	end
+	if exist(options,'colorbarwidth'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarwidth',1);
+		position=get(c,'Position');
+		dx=position(3);
+		newdx=dx*alpha;
+		position(1)=position(1)+(dx-newdx)/2;
+		position(3)=newdx;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'colorbarheight'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarheight',1);
+		position=get(c,'Position');
+		dy=position(4);
+		newdy=dy*alpha;
+		position(2)=position(2)+(dy-newdy)/2;
+		position(4)=newdy;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'cbYTickLabel');
+		tick_vals=getfieldvalue(options,'cbYTickLabel');
+		if ~isnumeric(tick_vals) & strcmp(tick_vals,'on')
+			tick_vals=get(c,'YTick')';
+			if exist(options,'log')
+				logval= getfieldvalue(options,'log');
+				for i= 1:size(tick_vals,1)
+					tick_vals(i)= logval^(tick_vals(i));
+				end
+			elseif size(tick_vals,1) == 3
+				tick_vals=[tick_vals(1); mean(tick_vals(1:2)); tick_vals(2); ...
+					mean(tick_vals(2:3)); tick_vals(3)];
+				set(c,'YTick',tick_vals);
+			end
+		end
+		labels = cell(1,size(tick_vals,1));
+		for i = 1:size(tick_vals,1)
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+		end
+		set(c,'YTickLabel',labels);
+	end
+
+elseif getfieldvalue(options,'colorbar',1)==0,
+	colorbar('off');
+else
+	%do nothing
+	
+end
+
+
+%area
+if exist(options,'area'),
+	antzoom(getfieldvalue(options,'area'));
+end
+
+%expdisp
+filename=(getfieldvalue(options,'expdisp'));
+style=(getfieldvalue(options,'expstyle'));
+for i=1:length(getfieldvalue(options,'expdisp')),
+	filenamei=filename{i};
+	stylei=style{i};
+	expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+end
+
+%text (default value is empty, not NaN...)
+if exist(options,'text');
+	textstring=getfieldvalue(options,'text');
+	textweight=getfieldvalue(options,'textweight','b');
+	textsize=getfieldvalue(options,'textsize');
+	textcolor=getfieldvalue(options,'textcolor');
+	textposition=getfieldvalue(options,'textposition');
+	textrotation=getfieldvalue(options,'textrotation');
+	for i=1:length(getfieldvalue(options,'text'));
+		textstringi=textstring{i};
+		textweighti=textweight{i};
+		textsizei=textsize{i};
+		textcolori=textcolor{i};
+		textpositioni=textposition{i};
+		textrotationi=textrotation{i};
+		h=text(textpositioni(1),textpositioni(2),10,textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
+		set(h,'Clipping','on'); %prevent text from appearing outside of the box
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	northarrow(getfieldvalue(options,'northarrow'));
+end
+
+%Scale ruler
+if exist(options,'scaleruler'),
+	scaleruler(options);
+end
+
+%streamliness
+if exist(options,'streamlines'),
+	plot_streamlines(md,options);
+end
+
+%contours
+if exist(options,'contourlevels'),
+	plot_contour(md,data,options);
+end
+
+%YTickLabel
+if exist(options,'yticklabel'),
+	set(gca,'YTickLabel',getfieldvalue(options,'YTickLabel'));
+end
+
+%XTickLabel
+if exist(options,'xticklabel'),
+	set(gca,'XTickLabel',getfieldvalue(options,'XTickLabel'));
+end
+
+%xtick
+if exist(options,'xtick'),
+	set(gca,'xtick',getfieldvalue(options,'xtick'));
+end
+
+%ytick
+if exist(options,'ytick'),
+	set(gca,'ytick',getfieldvalue(options,'ytick'));
+end
+
+%Axis positions
+if exist(options,'offsetaxispos'),
+	offset=getfieldvalue(options,'offsetaxispos');
+	P=get(gca,'pos');
+	P(1)=P(1)+offset(1);
+	P(2)=P(2)+offset(2);
+	P(3)=P(3)+offset(3);
+	P(3)=P(4)+offset(4);
+	set(gca,'pos',P);
+end
+if exist(options,'axispos'),
+	Axis=getfieldvalue(options,'axispos');
+	hold on
+	set(gca,'pos',Axis);
+end
+
+
+%position of figure
+if exist(options,'figposition'),
+	
+	figposition=getfieldvalue(options,'figposition');
+	if ischar(figposition),
+		if strcmpi(figposition,'larour'),
+			set(gcf,'Position',[1604 4 1594 1177]);
+		elseif strcmpi(figposition,'larour2'),
+			set(gcf,'Position',[756    62   827   504]);
+		elseif strcmpi(figposition,'mathieu'),
+			set(gcf,'Position',[300 1 1580 1150]);
+		elseif strcmpi(figposition,'fullscreen'),
+			set(gcf,'Position',get(0,'ScreenSize'));
+		elseif strcmpi(figposition,'halfright'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			set(gcf,'Position',fix([left+widt/2 bott widt/2 heig]));
+		elseif strcmpi(figposition,'halfleft'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			set(gcf,'Position',fix([left bott widt/2 heig]));
+		elseif strcmpi(figposition,'square'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=min(screen(3)-25,screen(4)-25);
+			set(gcf,'Position',fix([left+(screen(3)-widt) bott widt widt]));
+		elseif strcmpi(figposition,'portrait'),
+			%reformat with letter paper size (8.5" x 11")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			portrait=fix([left+widt-(heig*8.5/11) bott heig*8.5/11 heig]);
+			set(gcf,'Position',portrait)
+		elseif strcmpi(figposition,'landscape'),
+			%reformat with letter paper size (8.5" x 11")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			landscape=fix([left+widt-(heig*11/8.5) bott heig*11/8.5 heig]);
+			set(gcf,'Position',landscape)
+		else
+			disp('''figposition'' string not supported yet');
+		end
+	else
+		set(gcf,'Position',figposition);
+	end
+
+end
+
+%axes position
+if exist(options,'axesPosition')
+	set(gca,'Position',getfieldvalue(options,'axesPosition'));
+end
+
+%showregion
+if strcmpi(getfieldvalue(options,'showregion','off'),'on'),
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+	%get current plos position
+	cplotpos=get(maingca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	axes('pos',PosInset);
+	axis equal off
+	%box off
+	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+		A=expread([ jplsvn() '/projects/Exp/GreenlandBoxFront.exp']);
+		[A.x A.y]=ll2xy(A.x,A.y,+1,45,70);
+		A.x = A.x(1:30:end);
+		A.y = A.y(1:30:end);
+	elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+		A=expread([ jplsvn() '/projects/Exp/Antarctica.exp']);
+	else
+		error('applyoptions error message: hemisphere not defined');
+	end
+	offset=3*10^4;
+	Ax=[min(A.x)-offset max(A.x)+offset];
+	Ay=[min(A.y)-offset max(A.y)+offset];
+	%if we are zooming on a basin, don't take the mesh for the boundaries!
+	if exist(options,'basin'),
+		[mdx mdy]=basinzoom(options);
+	else
+		mdx=[min(md.mesh.x)-offset max(md.mesh.x)+offset];
+		mdy=[min(md.mesh.y)-offset max(md.mesh.y)+offset];
+	end
+	line(A.x,A.y,ones(size(A.x)),'color','b');
+	patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
+	patch([mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+	colorbar('off');
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
+
+%flag edges of a partition
+if exist(options,'partitionedges')
+	[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
+	xsegments=xsegments*getfieldvalue(options,'unit',1);
+	ysegments=ysegments*getfieldvalue(options,'unit',1);
+	color=getfieldvalue(options,'partitionedgescolor','r-');
+	linewidth=getfieldvalue(options,'linewidth',1);
+	hold on;
+	for i=1:length(xsegments),
+		plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
+	end
+end
+
+%Scatter
+if exist(options,'scatter')
+	data=getfieldvalue(options,'scatter');
+	hold on
+	plot_scatter(data(:,1),data(:,2),getfieldvalue(options,'scattersize',3),data(:,3),options);
+end
+
+%backgroundcolor
+set(gca,'color',getfieldvalue(options,'backgroundcolor','none'));
+
+%figurebackgrounbcolor
+set(gcf,'color',getfieldvalue(options,'figurebackgroundcolor','w'));
+
+%lighting
+if strcmpi(getfieldvalue(options,'light','off'),'on'),
+	set(gca,'FaceLighting','gouraud','FaceColor','interp','AmbientStrength',0.5);
+	light('Position',[0 0.1 0.1],'Style','infinite');
+end
+
+%cloud of points: 
+if exist(options,'cloud'),
+	field=getfieldvalue(options,'cloud');
+	x=field(:,1);
+	y=field(:,2);
+	%unit multiplier:
+	if exist(options,'unit'),
+		unit=getfieldvalue(options,'unit');
+		x=x*unit;
+		y=y*unit;
+	end
+	hold on,p=plot(x,y,'k.');
+	markersize=getfieldvalue(options,'markersize',5);
+	color=getfieldvalue(options,'cloudcolor','k');
+	set(p,'Color',color);
+end
+
+%========================%
+%OK VERY LAST STEP: INSET|
+%========================%
+if exist(options,'inset'),
+
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.56 0.55 0.35 0.35]);
+	%get current plot position
+	cplotpos=get(gca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	%show pos
+	X1=getfieldvalue(options,'insetx',xlim);
+	Y1=getfieldvalue(options,'insety',ylim);
+	if strcmpi(getfieldvalue(options,'showinset','off'),'on')
+		line(X1([1 2 2 1 1]),Y1([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
+	end
+
+	%Get current figure
+	ax1=gca;
+
+	%plot inset
+	axes('pos',PosInset);
+	copyobj(get(ax1,'children'),gca);
+	patch('Faces',[1 2 3 4 1],'Vertices',[X1([1 2 2 1])' Y1([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
+
+	%applay options
+	options=removefield(options,'text',0);
+	options=removefield(options,'title',0);
+	options=removefield(options,'xlabel',0);
+	options=removefield(options,'ylabel',0);
+	options=removefield(options,'inset',0);
+	options=removefield(options,'offsetaxispos',0);
+	options=removefield(options,'showregion',0);
+	options=changefieldvalue(options,'colorbar',0);
+	options=changefieldvalue(options,'latlon','off');
+	options=changefieldvalue(options,'axis','equal off');
+	options=changefieldvalue(options,'xlim',getfieldvalue(options,'insetx',xlim));
+	options=changefieldvalue(options,'ylim',getfieldvalue(options,'insety',ylim));
+	applyoptions(md,data,options);
+
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/arrow.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/arrow.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/arrow.m	(revision 13101)
@@ -0,0 +1,60 @@
+function arrow(x0,y0,x1,y1,varargin)
+%ARROW - plot arrow, using (x0,y0) and (x1,y1) as initial and end points. options can be specified.
+%
+%   Usage:
+%      arrow(x1,y1,x2,y2,options)
+%      where options is a lit of paired arguments of string OR enums
+%      options can be: 
+%            'ratio': default .5 (ratio headarrow/length)
+%            'widthratio': default is 1/10 of length
+
+
+%recover options
+options=pairoptions(varargin{:});
+ratio=getfieldvalue(options,'ratio',.5);
+widthratio=getfieldvalue(options,'widthratio',.1);
+color=getfieldvalue(options,'color','k');
+
+%compute some values out of (x1,y1) and (x2,y2)
+length=sqrt((x1-x0)^2+(y1-y0)^2);
+width=length*widthratio;
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0; y(1)=y0;
+x(2)=x1; y(2)=y1;
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],color);
+set(p1,'EdgeColor',color); set(p1,'FaceColor',color);
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],color);
+set(p2,'EdgeColor',color); set(p2,'FaceColor',color);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/checkplotoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/checkplotoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/checkplotoptions.m	(revision 13101)
@@ -0,0 +1,206 @@
+function options=checkplotoptions(md,options);
+%PARSE_OPTIONS - build a structure that holds all plot options
+%
+%   Usage:
+%      options=checkplotoptions(md,options);
+%
+%   See also: PLOTMODEL
+
+%units
+if exist(options,'unit'),
+	if strcmpi(getfieldvalue(options,'unit'),'km')
+		options=changefieldvalue(options,'unit',10^-3);
+	end
+	if strcmpi(getfieldvalue(options,'unit'),'100km')
+		options=changefieldvalue(options,'unit',10^-5);
+	end
+
+end
+
+%density
+if exist(options,'density'),
+	density=getfieldvalue(options,'density');
+	options=changefieldvalue(options,'density',abs(ceil(density)));
+end
+
+%Show section
+if exist(options,'showsection'),
+	if strcmpi(getfieldvalue(options,'showsection'),'on')
+		options=changefieldvalue(options,'showsection',4);
+	end
+end
+
+%smooth values
+if exist(options,'smooth'),
+	if strcmpi(getfieldvalue(options,'smooth'),'on')
+		options=changefieldvalue(options,'smooth',0);
+	end
+end
+
+%contouronly values
+if exist(options,'contouronly'),
+	if strcmpi(getfieldvalue(options,'contouronly'),'on')
+		options=changefieldvalue(options,'contouronly',1);
+	end
+end
+
+%Colorbar;
+if exist(options,'colorbar'),
+	if strcmpi(getfieldvalue(options,'colorbar'),'on')
+		options=changefieldvalue(options,'colorbar',1);
+	elseif strcmpi(getfieldvalue(options,'colorbar'),'off')
+			options=changefieldvalue(options,'colorbar',0);
+	end
+end
+	
+%text
+if exist(options,'text'),
+	%1: textvalue
+	textvalues=getfieldvalue(options,'text');
+	%ischar if only one expstyle -> create a cell
+	if ischar(textvalues),
+		textvalues={textvalues};
+		numtext=1;
+	elseif iscell(textvalues),
+		numtext=length(textvalues);
+	else
+		error('plot error message: ''text'' option should be either a string or a cell');
+	end
+
+	%2: textweight
+	if exist(options,'textweight'),
+		textweightvalues=getfieldvalue(options,'textweight');
+		%ischar if only one textweight -> create a cell
+		if ischar(textweightvalues),
+			textweightvalues={textweightvalues};
+		elseif ~iscell(textweightvalues);
+			error('plot error message: ''textweight'' option should be either a string or a cell');
+		end
+	else
+		textweightvalues={'n'};
+	end
+	textweightvalues=repmat(textweightvalues,1,numtext); textweightvalues(numtext+1:end)=[];
+	%3: textsize
+	if exist(options,'textsize'),
+		textsizevalues=getfieldvalue(options,'textsize');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textsizevalues),
+			textsizevalues={textsizevalues};
+		elseif ~iscell(textsizevalues);
+			error('plot error message: ''textsize'' option should be either a number or a cell');
+		end
+	else
+		textsizevalues={14};
+	end
+	textsizevalues=repmat(textsizevalues,1,numtext); textsizevalues(numtext+1:end)=[];
+	%4: textcolor
+	if exist(options,'textcolor'),
+		textcolorvalues=getfieldvalue(options,'textcolor');
+		%ischar if only one textcolor -> create a cell
+		if ischar(textcolorvalues),
+			textcolorvalues={textcolorvalues};
+		elseif ~iscell(textcolorvalues);
+			error('plot error message: ''textcolor'' option should be either a string or a cell');
+		end
+	else
+		textcolorvalues={'k'};
+	end
+	textcolorvalues=repmat(textcolorvalues,1,numtext); textcolorvalues(numtext+1:end)=[];
+	%4: textposition
+	if exist(options,'textposition'),
+		textpositionvalues=getfieldvalue(options,'textposition');
+		%ischar if only one textposition -> create a cell
+		if isnumeric(textpositionvalues),
+			textpositionvalues={textpositionvalues};
+		elseif ~iscell(textpositionvalues);
+			error('plot error message: ''textposition'' option should be either a string or a cell');
+		end
+	else
+		error('plot error message: ''textposition'' option is missing');
+	end
+	%6: textrotation
+	if exist(options,'textrotation'),
+		textrotationvalues=getfieldvalue(options,'textrotation');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textrotationvalues),
+			textrotationvalues={textrotationvalues};
+		elseif ~iscell(textrotationvalues);
+			error('plot error message: ''textrotation'' option should be either a number or a cell');
+		end
+	else
+		textrotationvalues={0};
+	end
+	textrotationvalues=repmat(textrotationvalues,1,numtext); textrotationvalues(numtext+1:end)=[];
+	options=changefieldvalue(options,'text',textvalues);
+	options=changefieldvalue(options,'textsize',textsizevalues);
+	options=changefieldvalue(options,'textweight',textweightvalues);
+	options=changefieldvalue(options,'textcolor',textcolorvalues);
+	options=changefieldvalue(options,'textposition',textpositionvalues);
+	options=changefieldvalue(options,'textrotation',textrotationvalues);
+end
+
+%expdisp
+expdispvaluesarray=cell(0,0);
+expstylevaluesarray=cell(0,0);
+expstylevalues=cell(0,0);
+if exist(options,'expstyle'),
+	expstylevalues=getfieldvalue(options,'expstyle');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expstylevalues),
+		expstylevalues={expstylevalues};
+	end
+end
+if exist(options,'expdisp'),
+	expdispvalues=getfieldvalue(options,'expdisp');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expdispvalues),
+		expdispvalues={expdispvalues};
+	end
+	for i=1:length(expdispvalues)
+		expdispvaluesarray{end+1}=expdispvalues{i};
+		if (length(expstylevalues)>=i),
+			expstylevaluesarray{end+1}=expstylevalues{i};
+		else
+			expstylevaluesarray{end+1}='g-';
+		end
+	end
+end
+options=changefieldvalue(options,'expstyle',expstylevaluesarray);
+options=changefieldvalue(options,'expdisp',expdispvaluesarray);
+
+%latlonnumbering
+if exist(options,'latlonclick'),
+	if strcmpi(getfieldvalue(options,'latlonclick'),'on')
+		options=changefieldvalue(options,'latlonclick',1);
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	if strcmpi(getfieldvalue(options,'northarrow'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'northarrow',[min(md.mesh.x)+1/6*Lx   min(md.mesh.y)+5/6*Ly   1/15*Ly   0.25   1/250*Ly]);
+	end
+end
+
+%scale ruler
+if exist(options,'scaleruler'),
+	if strcmpi(getfieldvalue(options,'scaleruler'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'scaleruler',[min(md.mesh.x)+6/8*Lx   min(md.mesh.y)+1/10*Ly   10^(ceil(log10(Lx)))/5 floor(Lx/100) 5]);
+	end
+end
+
+%Log scale (LOTS of changes to be performed
+if exist(options,'log'),
+	if exist(options,'caxis')
+		options=changefieldvalue(options,'caxis',log(getfieldvalue(options,'caxis'))/log(getfieldvalue(options,'log')));
+	end
+	options=changefieldvalue(options,'cutoff',log(getfieldvalue(options,'cutoff',1.5))/log(getfieldvalue(options,'log')));
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/getcolormap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/getcolormap.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/getcolormap.m	(revision 13101)
@@ -0,0 +1,55 @@
+function map = getcolormap(options)
+%GETCOLORMAP - get colormap from options
+%
+%   Usage:
+%      map = getcolormap(options)
+
+%default is jet
+if ~exist(options,'colormap'),
+	map = jet;
+	return
+end
+
+map = getfieldvalue(options,'colormap');
+if isnumeric(map);
+	%user provided a full colormap
+	return;
+end
+
+%OK this is an in-house colormap
+if ~ischar(map), error('colormap format not supported'); end
+
+if strcmpi(map,'Ala'),
+	map = jet(256);
+	map = map(128:end,:);
+elseif strcmpi(map,'redblue'),
+	map = hsv(256);
+	map = rgb2hsv(map);
+	map(:,2)       = max(min( abs(map(:,1)-0.5)/0.5 ,1),0);
+	map(1:128,1)   = 0.7;
+	map(129:end,1) = 1;
+	map = hsv2rgb(map);
+elseif strcmpi(map,'Rignot'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+elseif strcmpi(map,'Rignot2'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+	map=flipud(map);
+elseif strcmpi(map,'Seroussi'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = flipud(map);
+	map = map(1:floor(0.7*size(map,1)),:);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+else
+	eval(['map = ' map ';']);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/haxby.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/haxby.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/haxby.m	(revision 13101)
@@ -0,0 +1,36 @@
+function map = haxby(m);
+%HAXBY - Haxby color map
+%   HAXBY(M) returns an M-by-3 matrix containing a colormap with Haxby's
+%   colors, commonly used for displaying bathymetry data.
+%   HAXBY, by itself, is the same length as the current colormap.
+%
+%   Colormap is based on the colors used by W. F. Haxby's Gravity
+%   field of World's oceans, 1985, developed for geoid and gravity maps.
+%   The version used here is formed from a linear interpolation of
+%   the GMT color table used by MB-System by David W. Caress and Dale N. Chayes.
+%   <http://www.ldeo.columbia.edu/res/pi/MB-System>
+
+if nargin < 1, m = size(get(gcf,'colormap'),1); end
+
+ncolors=11;
+c=[...
+	37     57   175
+	40    127   251
+	50    190   255
+	106   235   255
+	138   236   174
+	205   255   162
+	240   236   121
+	255   189    87
+	255   161    68
+	255   186   133
+	255   255   255];
+
+pp=1:(m-1)/(ncolors-1):m;
+r=interp1(pp,c(:,1),1:m);
+g=interp1(pp,c(:,2),1:m);
+b=interp1(pp,c(:,3),1:m);
+map=[r' g' b']/255;
+
+%Fix bug of interp1 (M. Morlighem)
+map(find(map>1))=1;
Index: /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/lbmap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/lbmap.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/colormaps/lbmap.m	(revision 13101)
@@ -0,0 +1,109 @@
+function map = lbmap(n,scheme)
+%LBMAP Returns specified Light-Bertlein colormap.
+%
+%   LBMAP(N,SCHEME) returns an Nx3 colormap. SCHEME can be one of the
+%   following strings:
+%
+%       'Blue'       Single-hue progression to purlish-blue (default)
+%       'BlueGray'   Diverging progression from blue to gray
+%       'BrownBlue'  Orange-white-purple diverging scheme
+%       'RedBlue'    Modified spectral scheme
+%
+%   If N is not specified, the size of the colormap is determined by the
+%   current figure. If no figure exists, MATLAB creates one.
+%
+%Example 1: 7-color single-hue blue (default)
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(7))
+%   colorbar
+%
+%Example 2: 11-color modified spectrum
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(11,'RedBlue'))
+%   colorbar
+%
+%   See also HSV, GRAY, HOT, BONE, COPPER, PINK, FLAG, COLORMAP, RGBPLOT.
+
+% Reference:
+% A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for
+% Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.
+% http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf
+
+% Copyright 2007-2010 The MathWorks, Inc.
+
+%defensive programming
+error(nargchk(0,2,nargin))
+error(nargoutchk(0,1,nargout))
+
+%defaults
+if nargin<2
+	scheme = 'Blue';
+end
+if nargin<1
+	n = size(get(gcf,'colormap'),1);
+end
+
+%valid schemes
+switch lower(scheme)
+	case 'blue'
+		baseMap = BlueMap;
+	case 'bluegray'
+		baseMap = BlueGrayMap;
+	case 'brownblue'
+		baseMap = BrownBlueMap;
+	case 'redblue'
+		baseMap = RedBlueMap;
+	otherwise
+		error(['Invalid scheme ' scheme])
+	end
+	idx1 = linspace(0,1,size(baseMap,1));
+	idx2 = linspace(0,1,n);
+	map = interp1(idx1,baseMap,idx2);
+
+function baseMap = BlueMap
+	baseMap = [243 246 248;
+	224 232 240;
+	171 209 236;
+	115 180 224;
+	35 157 213;
+	0 142 205;
+	0 122 192]/255;
+
+function baseMap = BlueGrayMap
+	%DivergingBlueGray
+	baseMap = [  0 170 227;
+	53 196 238;
+	133 212 234;
+	190 230 242;
+	217 224 230;
+	146 161 170;
+	109 122 129;
+	65  79  81]/255;
+
+function baseMap = BrownBlueMap
+	baseMap = [144 100  44;
+	187 120  54;
+	225 146  65;
+	248 184 139;
+	244 218 200;
+	241 244 245;
+	207 226 240;
+	160 190 225;
+	109 153 206;
+	70  99 174;
+	24  79 162]/255;
+
+function baseMap = RedBlueMap
+	baseMap = [175  53  71;
+	216  82  88;
+	239 133 122;
+	245 177 139;
+	249 216 168;
+	242 238 197;
+	216 236 241;
+	154 217 238;
+	68 199 239;
+	0 170 226;
+	0 116 188]/255;
Index: /issm/branches/trunk-jpl-damage/src/m/plot/kmlgroundoverlay.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/kmlgroundoverlay.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/kmlgroundoverlay.m	(revision 13101)
@@ -0,0 +1,61 @@
+function kmlgroundoverlay(md,options);
+%KMLGROUNDOVERLAY: create ground overlay image in kml format
+%
+%
+%    options: 
+%         kmlfilename
+%         imagename
+%
+%    Usage: 
+%         kmlgroundoverlay(md,'kmlfilename','temp.kml','imagename','greenland.jpeg');
+%
+
+%first figure out if lat and long were computed!
+if (isempty(md.mesh.lat) | isempty(md.mesh.long)),
+	error('kmlgroundoverlay error message: project x,y onto lat,long fields of model!');
+end
+
+%process kml options
+kmlfilename=getfieldvalue(options,'kmlfilename','tempfile.kml');
+kmlroot=getfieldvalue(options,'kmlroot','./');
+kmlimagename=getfieldvalue(options,'kmlimagename','tempimage');
+kmlimagetype=getfieldvalue(options,'kmlimagetype','png');
+kmlresolution=getfieldvalue(options,'kmlresolution',1);
+kmlfolder=getfieldvalue(options,'kmlfolder','Ground Overlay');
+kmlfolderdescription=getfieldvalue(options,'kmlfolderdescription','');
+kmlgroundoverlayname=getfieldvalue(options,'kmlgroundoverlayname','');
+kmlgroundoverlaydescription=getfieldvalue(options,'kmlgroundoverlaydescription','');
+
+%figure out  min and max for lat and long of this image:
+west=min(md.mesh.long);
+east=max(md.mesh.long);
+south=min(md.mesh.lat);
+north=max(md.mesh.lat);
+
+%print image at high resolution
+printmodel([kmlroot '/' kmlimagename],kmlimagetype,'trim','on','resolution',kmlresolution,'margin','off','frame','off');
+
+%now write kml file
+fid=fopen([kmlroot '/' kmlfilename],'w');
+
+fprintf(fid,'%s\n','<?xml version="1.0" encoding="UTF-8"?>');
+fprintf(fid,'%s\n','<kml xmlns="http://www.opengis.net/kml/2.2">');
+fprintf(fid,'%s\n','<Folder>');
+fprintf(fid,'%s%s%s\n','<name>',kmlfolder,'</name>');
+fprintf(fid,'%s%s%s\n','<description>',kmlfolderdescription,'</description>');
+fprintf(fid,'%s\n','<GroundOverlay>');
+fprintf(fid,'%s%s%s\n','<name>',kmlgroundoverlayname,'</name>');
+fprintf(fid,'%s\n','<description>',kmlgroundoverlaydescription,'</description>');
+fprintf(fid,'%s%s.%s%s\n','<Icon>',kmlimagename,kmlimagetype,'</Icon>');
+fprintf(fid,'%s\n','<LatLonBox>');
+fprintf(fid,'%s%f%s\n','<north>',north,'</north>');
+fprintf(fid,'%s%f%s\n','<south>',south,'</south>');
+fprintf(fid,'%s%f%s\n','<east>',east,'</east>');
+fprintf(fid,'%s%f%s\n','<west>',west,'</west>');
+fprintf(fid,'%s\n','<rotation>0</rotation>');
+fprintf(fid,'%s\n','</LatLonBox>');
+fprintf(fid,'%s\n','</GroundOverlay>');
+fprintf(fid,'%s\n','</Folder>');
+fprintf(fid,'%s\n','</kml>');
+
+fclose(fid);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/latlonoverlay.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/latlonoverlay.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/latlonoverlay.m	(revision 13101)
@@ -0,0 +1,149 @@
+function latlonoverlay(md,options)
+%LATLONOVERLAY - overlay latitude and longitude lines on current figure
+%
+%   latstep,lonstep, in latitude and longitude degreees, between two latitudinal, longitudinal profiles.
+%   color: [1 1 1] for example
+%   resolution: profile resolution ( in lat,lon degrees) 
+%   gap: gap (in meters) to plug lat,lon degree numbers;
+%
+%   Usage:
+%      latlonoverlay(options)
+
+%get options
+latlon=getfieldvalue(options,'latlon');
+numbering=getfieldvalue(options,'latlonnumbering','off');
+latlonclick=getfieldvalue(options,'latlonclick',0);
+fontsize=getfieldvalue(options,'fontsize',16);
+
+%recover arguments (set default parameters if needed)
+%1: latlon
+if ~iscell(latlon),
+	if ischar(latlon) & strcmpi(latlon,'on'),
+		%defaults
+		latstep=3; lonstep=3;
+		resolution=0.1;
+		color=[1 0 1];
+	else return; end
+else
+	if length(latlon)<2
+		error('latlonoverlay error message: at least 2 arguments are required, or use ''on'' option.');
+	end
+	if length(latlon)>3, color=latlon{4};      else color=[1 1 1]; end
+	if length(latlon)>2, resolution=latlon{3}; else resolution=0.1;end
+	latstep=latlon{1};
+	lonstep=latlon{2};
+end
+
+%2: numbering
+if ~iscell(numbering) & isnan(numbering),
+	numbering=false;
+else
+	if ~iscell(numbering),
+		if strcmpi(char(numbering),'on'),
+			%defaults
+			latgap=2; longap=2;
+			colornumber=color;
+			latangle=0; lonangle=0;
+			numbering=true;
+		else
+			numbering=false;
+		end
+	else
+		latgap=numbering{1}; longap=numbering{2};
+		colornumber=numbering{3};
+		latangle=numbering{4}; lonangle=numbering{5};
+		numbering=true;
+	end
+end
+
+%what are the x and y limits
+xlimits=getfieldvalue(options,'xlim',xlim);
+ylimits=getfieldvalue(options,'ylim',ylim);
+
+%lat
+for lat=-90:latstep:90
+	longitudes=0:resolution:360;
+	latitudes =lat*ones(size(longitudes));
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if lat<0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if lat>0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else error('field hemisphere should either be ''n'' or ''s'''); end
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering
+		ind=length(x)-2*latgap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+latangle,360);
+			if lat<0, label=[num2str(abs(lat)) '^{\circ}S'];
+			else      label=[num2str(abs(lat)) '^{\circ}N']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-latgap),y(1:ind-latgap),'Color',color);hold on;
+			line(x(ind+latgap:end),y(ind+latgap:end),'Color',color);
+			set(gcf,'InvertHardcopy','off');
+		end
+
+	end
+end
+
+%lon
+for lon=-180:lonstep:180
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		latitudes =0:resolution:90;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		latitudes =-90:resolution:0;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s'''); 
+	end
+
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering,
+		ind=length(x)-2*longap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+lonangle,360);
+			if lon<0, label=[num2str(abs(lon)) '^{\circ}W'];
+			else      label=[num2str(abs(lon)) '^{\circ}E']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-longap),y(1:ind-longap),'Color',color);hold on;
+			line(x(ind+longap:end),y(ind+longap:end),'Color',color);
+		end
+
+	end
+end
+
+%Back to original limits
+xlim(xlimits);
+ylim(ylimits);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/northarrow.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/northarrow.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/northarrow.m	(revision 13101)
@@ -0,0 +1,76 @@
+function northarrow(structure)
+%NORTHARROW - overlay an arrow pointing north on the current plot
+%
+%   Usage:
+%      northarrow(structure)
+
+%Go through structure and fill missing arguments
+if length(structure)<3
+	error('plotmodel error message: the position or the length of the North arrow is missing');
+elseif length(structure)==3
+	structure(4)=0.5; %default ratio headarrow/length
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==4
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==5
+	structure(6)=16; %default fontsize
+elseif length(structure)>6
+	error('plotmodel error message: to many input arguments for northarrow: [x0 y0 length [ratio width fontsize]]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengtharrow=structure(3);
+ratio=structure(4);
+width=structure(5);
+fontsize=structure(6);
+
+%Figure out angle to point towards north
+ang=atan2(y0,x0);
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0;
+y(1)=y0;
+
+x(2)=x(1)+lengtharrow*cos(ang);
+y(2)=y(1)+lengtharrow*sin(ang);
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],'Black');
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],'Black');
+
+%Text North
+xN=max([A(1) D(1) E(1) F(1) G(1)])+ratio/3*abs(lengtharrow);
+yN=mean([A(2) F(2) H(2)]);
+text(xN,yN,'North','FontSize',fontsize,'FontWeight','b');
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_BC.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_BC.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_BC.m	(revision 13101)
@@ -0,0 +1,41 @@
+function plot_BC(md,options,width,i,data);
+
+%plot neuman
+plot_icefront(md,options,width,i,data)
+
+hold on
+
+%plot dirichlets
+h1=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	'ro','MarkerSize',14,'MarkerFaceColor','r');
+h2=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	'bo','MarkerSize',10,'MarkerFaceColor','b');
+h3=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	'yo','MarkerSize',6 ,'MarkerFaceColor','y');
+
+%update legend
+[legend_h,object_h,plot_h,text_strings]=legend();
+legend('off');
+text_strings{end+1}='vx Dirichlet';
+text_strings{end+1}='vy Dirichlet';
+if h3, text_strings{end+1}='vz Dirichlet'; end
+plot_h(end+1)=h1;
+plot_h(end+1)=h2;
+if h3, plot_h(end+1)=h3; end
+legend(plot_h,text_strings,'location','NorthEast')
+
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_basaldrag.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_basaldrag.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_basaldrag.m	(revision 13101)
@@ -0,0 +1,53 @@
+function plot_basaldrag(md,options,width,i,type);
+
+%PLOT_BASALDRAG - plot basal drag
+%
+%   Usage:
+%      plot_basaldrag(md,options,width,i,type);
+%
+%   See also: PLOTMODEL
+
+%check layer
+if md.mesh.dimension==3,
+	if getfieldvalue(options,'layer',1)~=1;
+		disp('plot_basaldrag warning: basal drag is displayed in the lower layer')
+		changefieldvalue(options,'layer',1);
+	end
+end
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+if strcmpi(type,'basal_drag')
+	ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+elseif strcmpi(type,'basal_dragx')
+	ub=md.initialization.vx/md.constants.yts;
+elseif strcmpi(type,'basal_dragy')
+	ub=md.initialization.vy/md.constants.yts;
+end
+
+%compute basal drag
+drag=(max(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed),0)).^r.*(md.friction.coefficient).^2.*ub.^s/1000;
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,drag,options,width,i);
+	return;
+else
+
+	%process data and model
+	[x y z elements is2d isplanet]=processmesh(md,[],options);
+	[basal_drag datatype]=processdata(md,drag,options);
+
+	%plot basaldrag
+	subplot(width,width,i); 
+	plot_unit(x,y,z,elements,basal_drag,is2d,isplanet,datatype,options);
+
+	%apply options
+	options=addfielddefault(options,'title','Basal drag [kPa]');
+	options=addfielddefault(options,'view',2);
+	applyoptions(md,basal_drag,options);
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_boundaries.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_boundaries.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_boundaries.m	(revision 13101)
@@ -0,0 +1,39 @@
+function plot_boundaries(md,options,width,i);
+%PLOT_BOUNDARIES - plot mesh boundaries
+%
+%   Usage:
+%      plot_boundaries(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+subplot(width,width,i); 
+
+%process data and model
+if getfieldvalue(options,'layer',0)
+	options=removefield(options,'layer',1);
+end
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');hold on;
+end
+
+%plot rifts if present: 
+if isstruct(md.rifts.riftstruct),
+	for i=1:size(md.rifts.riftstruct,1),
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'r.-');
+		end
+		text(x(segments(floor(size(segments,1)/4),1)),y(segments(floor(size(segments,1)/4),1)),['Rift #' num2str(i)]);
+		%point out the tips
+		plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'b*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'b*');
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh boundaries');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_contour.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_contour.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_contour.m	(revision 13101)
@@ -0,0 +1,245 @@
+function plot_contour(md,datain,options);
+%PLOT_CONTOUR - plot contours of a given field
+%
+%   Usage:
+%      plot_contour(md,data,options);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+options=removefield(options,'log',0);
+[data datatype]=processdata(md,datain,options);
+
+%check is2d
+if ~is2d,
+	error('plot_contour error message: contour not supported for 3d meshes, project on a layer');
+end
+
+%first, process data: must be on nodes
+if datatype==1,
+	%elements -> take average
+	data=averaging(md,data,0);
+elseif datatype==2,
+	%nodes -> do nothing
+elseif datatype==3,
+	%quiver -> take norm
+	data=sqrt(sum(datain.*datain,2));
+else
+	error('datatype not supported yet');
+end
+
+%prepare colors
+if exist(options,'contouronly')
+	%remove the previous plots
+	cla
+end
+color=getfieldvalue(options,'contourcolor','y');
+linewidth=getfieldvalue(options,'linewidth',1);
+
+%get contours levels
+contourlevels=getfieldvalue(options,'contourlevels');
+if isnumeric(contourlevels),
+	levels=round_ice(linspace(max(data),min(data),contourlevels),2);
+else
+	levels=[];
+	for i=1:length(contourlevels)
+		levels(end+1)=contourlevels{i};
+	end
+	levels=sort(unique(levels),'descend');
+end
+numlevels=length(levels);
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=data(Seg1);
+Data2=data(Seg2);
+Data3=data(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+for i=1:numlevels
+
+	level=levels(i);
+
+	%find the segments that contain this value
+	pos1=(Range1(:,1)<level & Range1(:,2)>level);
+	pos2=(Range2(:,1)<level & Range2(:,2)>level);
+	pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+	%get elements
+	poselem12=(pos1 & pos2);
+	poselem13=(pos1 & pos3);
+	poselem23=(pos2 & pos3);
+	poselem=find(poselem12 | poselem13 | poselem23);
+	numelems=length(poselem);
+
+	%if no element has been flagged, skip to the next level
+	if numelems==0,
+		continue,
+	end
+
+	%go through the elements and build the coordinates for each segment (1 by element)
+	x1=zeros(numelems,1);
+	x2=zeros(numelems,1);
+	y1=zeros(numelems,1);
+	y2=zeros(numelems,1);
+	edge_l=zeros(numelems,2);
+
+	for j=1:numelems,
+
+		weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+		weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+		weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+		if poselem12(poselem(j));
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg2_num(poselem(j));
+
+		elseif poselem13(poselem(j)),
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+
+		elseif poselem23(poselem(j)),
+
+			x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg2_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+		else
+			%it shoud not go here
+		end
+	end
+
+	%now that we have the segments, we must try to connect them...
+
+	%loop over the subcontours
+	while ~isempty(edge_l),
+
+		%take the right edge of the second segment and connect it to the next segments if any
+		e1=edge_l(1,1);   e2=edge_l(1,2);
+		xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+		%erase the lines corresponding to this edge
+		edge_l(1,:)=[];
+		x1(1)=[]; x2(1)=[];
+		y1(1)=[]; y2(1)=[];
+
+		[ro1,co1]=find(edge_l==e1);
+
+		while ~isempty(ro1)
+
+			if co1==1,
+				xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,2);
+
+			else
+				xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro1,:)=[];
+			x1(ro1)=[]; x2(ro1)=[];
+			y1(ro1)=[]; y2(ro1)=[];
+
+			%next connection
+			[ro1,co1]=find(edge_l==e1);
+		end
+
+		%same thing the other way (to the right)
+		[ro2,co2]=find(edge_l==e2);
+
+		while ~isempty(ro2)
+
+			if co2==1,
+				xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,2);
+			else
+				xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro2,:)=[];
+			x1(ro2)=[]; x2(ro2)=[];
+			y1(ro2)=[]; y2(ro2)=[];
+
+			%next connection
+			[ro2,co2]=find(edge_l==e2);
+		end
+
+		%we now have one subcontour ready to be plotted
+		zc=level*ones(length(xc)+1,1);
+		if getfieldvalue(options,'contouronly',0),
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat','linewidth',linewidth)];
+			hold on      
+		else
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth)];
+			hold on
+		end
+
+		% Update the CS data structure as per "contours.m"
+		% so that clabel works
+		c = horzcat(c,[level, xc'; length(xc), yc']);
+
+	end
+end
+
+%labels?
+if (~strcmpi(getfieldvalue(options,'contourticks','on'),'off') & ~isempty(c) & ~isempty(h))
+	if exist(options,'contouronly')
+		clabel(c,h);
+	else
+		clabel(c,h,'color',color,'FontSize',14);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_drivingstress.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_drivingstress.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_drivingstress.m	(revision 13101)
@@ -0,0 +1,24 @@
+function plot_drivingstress(md,options,width,i);
+%PLOT_DRIVINGSTRESS - plot driving stress
+%
+%   Usage:
+%      plot_drivingstress(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%get driving stress
+[sx sy s]=drivingstress(md);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[dstress datatype]=processdata(md,s,options);
+dstress=dstress/1000;
+
+%plot mesh quivervel
+subplot(width,width,i); 
+plot_unit(x,y,z,elements,dstress,is2d,isplanet,datatype,options)
+
+%apply options
+options=addfielddefault(options,'title','Driving stress [kPa]');
+options=addfielddefault(options,'view',2);
+applyoptions(md,dstress,options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_edges.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_edges.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_edges.m	(revision 13101)
@@ -0,0 +1,34 @@
+function plot_edges(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_edges(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+edges=md.mesh.edges;
+if isnan(edges)
+	error('edges in NaN')
+end
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+	text(sum(x(edges(:,1:2)),2)/2,sum(y(edges(:,1:2)),2)/2,sum(z(edges(:,1:2)),2)/2,...
+		num2str(transpose(1:size(edges,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	error('plot_edges: 3d plot of edges not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Edges');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementnumbering.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementnumbering.m	(revision 13101)
@@ -0,0 +1,57 @@
+function plot_elementnumbering(md,options,width,i);
+%PLOT_ELEMENTNUMBERING - plot element numbering
+%
+%   Usage:
+%      plot_elementnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:3)),2)/3,sum(y(elements(:,1:3)),2)/3,sum(z(elements(:,1:3)),2)/3,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:6)),2)/6,sum(y(elements(:,1:6)),2)/6,sum(z(elements(:,1:6)),2)/6,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Element numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementstype.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementstype.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_elementstype.m	(revision 13101)
@@ -0,0 +1,131 @@
+function plot_elementstype(md,options,width,i);
+%PLOT_ELEMENTSTYPE - plot elements type
+%
+%   Usage:
+%      plot_elementstype(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,md.flowequation.element_equation,options);
+
+%edgecolor?
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%plot
+subplot(width,width,i);
+
+if is2d
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
+	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal element
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn element
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
+	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn element
+	posMP=find(data==5);
+	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
+	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
+	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	posMS=find(data==6);
+	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
+	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	posPS=find(data==7);
+	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
+	p8=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',7,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	posNONE=find(data==0);
+	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
+	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p5 p6 p7 p8 p9],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements',...
+		'MacAyealPattyn''s elements','Stokes''s elements','MacAyealStokes''s elements','PattynStokes''s elements','None element');
+
+else
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
+	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal elements
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
+	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
+	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn elements
+	posP=find(data==5);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	PosPS=find(data==7);
+	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
+	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	PosMS=find(data==6);
+	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
+	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	PosNONE=find(data==0);
+	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
+	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p4 p5 p6 p7 p8],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements','Stokes''s elements',...
+		'MacAyealPattyn''s elements','PattynStokes''s elements','MacAyealStokes''s elements','None elements');
+end
+
+%apply options
+options=addfielddefault(options,'title','Elements type');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_gridded.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_gridded.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_gridded.m	(revision 13101)
@@ -0,0 +1,64 @@
+function plot_gridded(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_gridded(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+%Get xlim and ylim (used to extract radar image)
+xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+post=getfieldvalue(options,'posting',diff(xlim)/1000);
+
+%Interpolating data on grid
+[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+if size(data_grid,1)<3 | size(data_grid,2)<3,
+	error('data_grid size too small in plot_gridded, check posting and uni');
+end
+
+%Get and change colormap
+map    = getcolormap(options);
+lenmap = size(map,1);
+map    = [1 1 1; map];
+options=changefieldvalue(options,'colormap',map);
+
+%Process data_grid: add white in NaN and correct caxis accordingly
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+options = changefieldvalue(options,'cbYLim',[data_min data_max]);
+white   = data_min - (data_max-data_min)/(lenmap);
+options = changefieldvalue(options,'caxis',[white data_max]);
+data_grid(isnan(data_grid))=white;
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+%shading interp;
+h=imagesc(xlim,ylim,data_grid);set(gca,'YDir','normal');
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%Apply options
+applyoptions(md,data,options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightelements.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightelements.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightelements.m	(revision 13101)
@@ -0,0 +1,51 @@
+function plot_highlightelements(md,options,width,i);
+%PLOT_HIGHLIGHTELEMENTS - plot selected elements
+%
+%   Usage:
+%      plot_highlightelements(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightelements warning : highlight option empty, not element highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Elements');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightvertices.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightvertices.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_highlightvertices.m	(revision 13101)
@@ -0,0 +1,46 @@
+function plot_highlightvertices(md,options,width,i);
+%PLOT_HIGHLIGHTVERTICES - plot selected vertices
+%
+%   Usage:
+%      plot_highlightvertices(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[nodenumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightvertices warning : highlight option empty, not node highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Nodes');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_icefront.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_icefront.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_icefront.m	(revision 13101)
@@ -0,0 +1,106 @@
+function plot_icefront(md,options,width,i,data);
+%PLOT_ICEFRONT - plot segment on neumann BC
+%
+%   Usage:
+%      plot_icefront(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+icefront=md.diagnostic.icefront;
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3bis=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h4=plot(xstart,ystart,'r*');
+else
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h2=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3bis=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	zstart=mean(z(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zeros(numel(xstart),1)); hold on;
+	h4=plot3(xstart,ystart,zstart,'r*');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,h3,h3bis,q],'element on ice front (Water)','element on ice front (Air)','element on ice front (Ice)','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Neumann boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_importancefactors.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_importancefactors.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_importancefactors.m	(revision 13101)
@@ -0,0 +1,83 @@
+function plot_importancefactors(md,options,width,ii);
+%PLOT_IMPORTANCEFACTORS - plot importance factors
+%
+%   Usage:
+%      plot_importancefactors(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%first recover design variable descriptor
+if exist(options,'designvariable'),
+	descriptor=getfieldvalue(options,'designvariable');
+else
+	error('plot_importancefactors error message: Need to supply design variable descriptor');
+end
+descriptorlength=length(descriptor);
+
+%then recover responsfunction name
+if exist(options,'responsefunction'),
+	responsefunctiondescriptor=getfieldvalue(options,'responsefunction');
+else
+	error('plot_importancefactors error message: Need to supply response function descriptor');
+end
+
+%go through all response functions and find the one corresponding to the correct responsefunctiondescriptor
+responsefunctions=md.qmu.results{2};
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsefunctiondescriptor),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('plot_importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.desvar,1);
+
+%Now recover response to the correct desgin variable
+importancefactors=zeros(md.qmu.numberofpartitions,1);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.desvar{i};
+	if strncmpi(desvar,descriptor,descriptorlength),
+		count=count+1;
+		importancefactors(count)=responsefunctions.impfac(i);
+	end
+end
+if count==0,
+	error('plot_importancefactors error message: could not find to response functions with corresponding design variable');
+end
+
+%log?
+if exist(options,'log'),
+	logvalue=getfieldvalue(options,'log');
+	importancefactors=log(importancefactors)/log(logvalue);
+end
+
+%Ok, get partitioning.
+[epart npart]=MeshPartition(md,md.qmu.numberofpartitions);
+
+%distribute importance factor
+nodeimportance=importancefactors(npart);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%standard plot:
+subplot(width,width,ii);
+
+%ok, plot nodeimportance now.
+if is2d,
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', nodeimportance,'FaceColor','interp','EdgeColor',edgecolor);
+else
+	error('plot_importancefactors error message: 3d meshes not supported yet');
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_manager.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_manager.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_manager.m	(revision 13101)
@@ -0,0 +1,204 @@
+function plot_manager(md,options,subplotwidth,nlines,ncols,i);
+%PLOT__MANAGER - distribute the plots, called by plotmodel
+%
+%   Usage:
+%      plot_manager(md,options,subplotwidth,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT
+
+%parse options and get a structure of options. 
+options=checkplotoptions(md,options);
+
+%get data to be displayed
+data=getfieldvalue(options,'data');
+
+%figure out if this is a special plot
+if ischar(data),
+
+	switch data,
+
+		case 'boundaries',
+			plot_boundaries(md,options,subplotwidth,i);
+			return;
+		case 'BC',
+			plot_BC(md,options,subplotwidth,i,data);
+			return;
+		case 'edges'
+			plot_edges(md,options,subplotwidth,i,data)
+			return
+		case 'elementnumbering',
+			plot_elementnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightelements',
+			plot_highlightelements(md,options,subplotwidth,i);
+			return;
+		
+		case 'qmumean',
+			plot_qmumean(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmustddev',
+			plot_qmustddev(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmuhistnorm',
+			plot_qmuhistnorm(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmu_mass_flux_segments',
+			plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+			return;
+
+		case 'part_hist',
+			plot_parthist(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_n',
+			plot_parthistn(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_w',
+			plot_parthistw(md,options,nlines,ncols,i);
+			return;
+		case 'elements_type',
+			plot_elementstype(md,options,subplotwidth,i);
+			return;
+		case 'vertexnumbering',
+			plot_vertexnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightvertices',
+			plot_highlightvertices(md,options,subplotwidth,i);
+			return;
+		case {'basal_drag','basal_dragx','basal_dragy'},
+			plot_basaldrag(md,options,subplotwidth,i,data);
+			return;
+		case 'driving_stress',
+			plot_drivingstress(md,options,subplotwidth,i);
+			return;
+		case 'mesh',
+			plot_mesh(md,options,nlines,ncols,i);
+			return;
+		case 'none',
+			if ~exist(options,'overlay'),
+				plot_none(md,options,nlines,ncols,i);
+				return;
+			end
+		case 'penalties',
+			plot_penalties(md,options,subplotwidth,i);
+			return;
+		case 'partition',
+			plot_partition(md,options,nlines,ncols,i);
+			return;
+		case 'referential',
+			plot_referential(md,options,nlines,ncols,i);
+			return;
+		case 'riftvel',
+			plot_riftvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftnumbering',
+			plot_riftnumbering(md,options,nlines,ncols,i);
+			return;
+		case 'rifts',
+			plot_rifts(md,options,nlines,ncols,i);
+			return;
+		case 'riftrelvel',
+			plot_riftrelvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftpenetration',
+			plot_riftpenetration(md,options,nlines,ncols,i);
+			return;
+		case 'riftfraction',
+			plot_riftfraction(md,options,nlines,ncols,i);
+			return;
+		case 'sarpwr',
+			plot_sarpwr(md,options,subplotwidth,i)
+			return
+		case 'icefront'
+			plot_icefront(md,options,subplotwidth,i,data)
+			return
+		case 'segments'
+			plot_segments(md,options,subplotwidth,i,data)
+			return
+		
+		case 'quiver'
+			data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
+
+		case {'strainrate_tensor','strainrate','strainrate_principal','strainrate_principalaxis1','strainrate_principalaxis2','strainrate_principalaxis3',...
+				'stress_tensor','stress','stress_principal','stress_principalaxis1','stress_principalaxis2','stress_principalaxis3',...
+				'deviatoricstress_tensor','deviatoricstress','deviatoricstress_principal','deviatoricstress_principalaxis1','deviatoricstress_principalaxis2','deviatoricstress_principalaxis3'},
+			plot_tensor(md,options,subplotwidth,i,data);
+			return;
+		case 'thermaltransient_results',
+			plot_thermaltransient_results(md,options,subplotwidth,i);
+			return;
+		case 'transient_movie',
+			plot_transient_movie(md,options,subplotwidth,i);
+			return;
+		case 'transient_results',
+			plot_transient_results(md,options,subplotwidth,i);
+
+		case 'transient_field',
+			plot_transient_field(md,options,subplotwidth,i);
+			return;
+
+	otherwise,
+
+		if ismember(data,properties('model')),
+			data=eval(['md.' data ';']);
+		else
+			error('plot error message: data provided not supported yet. Type plotdoc for help');
+		end
+	end
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'overlay'),
+	plot_overlay(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'gridded'),
+	plot_gridded(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Profile plot
+if exist(options,'profile')
+	plot_profile(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,data,options);
+[data2 datatype]=processdata(md,data,options);
+
+%standard plot:
+subplot(nlines,ncols,i);
+
+%plot unit
+plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options);
+
+%apply all options
+if datatype==3,
+	options=changefieldvalue(options,'colorbar',2);
+	if exist(options,'contourlevels'),
+		data2=data;
+	end
+end
+
+applyoptions(md,data2,options);
+
+%do ground overlay on kml plot_unit? 
+if (strcmpi(getfieldvalue(options,'kmlgroundoverlay','off'),'on')),
+	if ((nlines*ncols~=1) | (i~=1)),
+		error('cannot kmlgroundoverlay on multi-plots');
+	end
+	
+	%call routine to build kml file and image that goes with it.
+	kmlgroundoverlay(md,options);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_mesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_mesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_mesh.m	(revision 13101)
@@ -0,0 +1,41 @@
+function plot_mesh(md,options,nlines,ncols,i);
+%PLOT_MESH - plot model mesh
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%retrieve some options
+linewidth=getfieldvalue(options,'linewidth',1);
+edgecolor=getfieldvalue(options,'edgecolor','black');
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+else
+	if ~isplanet,
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	else
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+		if (size(elements,2)==4), D=elements(:,4); else D=C; end
+		patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_none.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_none.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_none.m	(revision 13101)
@@ -0,0 +1,20 @@
+function plot_none(md,options,nlines,ncols,i);
+%PLOT_NONE - plot nothing, just apply options
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+return;
+
+options=addfielddefault(options,'colorbar','none');
+options=addfielddefault(options,'map','none');
+options=addfielddefault(options,'axis','equal');
+
+if exist(options,'overlay'),
+	plot_overlay(md,'none',options,nlines,ncols,i);
+	return;
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_overlay.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_overlay.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_overlay.m	(revision 13101)
@@ -0,0 +1,154 @@
+function plot_overlay(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_overlay(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+if strcmpi(data,'none'),
+	radaronly=1;
+	data=NaN*ones(md.mesh.numberofvertices,1);
+	datatype=1;
+else
+	radaronly=0;
+	[data datatype]=processdata(md,data,options);
+end
+
+%check is2d
+if ~is2d, 
+	error('buildoverlay error message: overlay not supported for 3d meshes, project on a layer');
+end
+if datatype==3,
+	error('buildoverlay error message: overlay not supported for quiver plots');
+end
+
+
+%radar power
+if ~any(isnan(md.radaroverlay.x)) & ~any(isnan(md.radaroverlay.y)) & ~any(isnan(md.radaroverlay.pwr)),
+	disp('plot_overlay info: the radar image held by the model is being used');
+	xlim=[min(md.radaroverlay.x) max(md.radaroverlay.x)];
+	ylim=[min(md.radaroverlay.y) max(md.radaroverlay.y)];
+else
+	disp('Extracting radar image...');
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)])/getfieldvalue(options,'unit',1);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)])/getfieldvalue(options,'unit',1);
+	options=addfielddefault(options,'xlim',xlim);
+	options=addfielddefault(options,'ylim',ylim);
+	md=radarpower(md,options);
+end
+contrast = getfieldvalue(options,'contrast',1);  
+radar = (md.radaroverlay.pwr).^(contrast);
+radar = radar./max(radar(:));
+%radar(find(radar==0))=1; %Change background from black to white
+
+%InterpFromMeshToGrid
+xmin=min(md.radaroverlay.x);
+ymax=max(md.radaroverlay.y);
+xspacing=(max(md.radaroverlay.x)-min(md.radaroverlay.x))/(length(md.radaroverlay.x));
+yspacing=(max(md.radaroverlay.y)-min(md.radaroverlay.y))/(length(md.radaroverlay.y));
+nlines=length(md.radaroverlay.y);
+ncols =length(md.radaroverlay.x);
+disp('Interpolating data on grid...');
+if radaronly,
+	x_m=xmin:xspacing:xmin+ncols*xspacing;
+	y_m=ymax-nlines*yspacing:yspacing:ymax;
+	data_grid=NaN*ones(nlines,ncols);
+else
+	[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),...
+		data,xmin,ymax,xspacing,yspacing,nlines,ncols,NaN);
+end
+
+%Process data_grid (For processing, it is better not to have nan)
+pos=find(isinf(data_grid));
+if ~isempty(pos),
+	disp('Warning: removing Infs from vector (probably log(0)?)');
+	data_grid(pos)=NaN;
+end
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+data_nan=find(isnan(data_grid));
+data_grid(data_nan)=data_min; 
+
+%Special colormaps that require hsv treatment
+colorm=getfieldvalue(options,'colormap','Rignot');
+if strcmpi(colorm,'Rignot') | strcmpi(colorm,'Seroussi') | strcmpi(colorm,'redblue')
+	if strcmpi(colorm,'Rignot'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=(data_grid-data_min)/(data_max-data_min+eps);
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'Seroussi'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=1-(data_grid-data_min)/(data_max-data_min+eps)*0.7;
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'redblue')
+		data_mean=data_min+(data_max-data_min)/2;
+		h=1*ones(size(data_grid));
+		h(find(data_grid<data_mean))=0.7;
+		s=max(min(abs(data_grid-data_mean)/(data_max-data_mean) ,1),0);
+	else
+		error('colormap not supported yet. (''Rignot'' and ''redblue'' are the only cupported colormaps)');
+	end
+	%(S) Saturation is 0 in NaNs
+	s(data_nan)=0;
+	%(V) intensity is based on radar image
+	v=radar; %use radar power as intensity
+
+	%Transform HSV to RGB
+	image_hsv=zeros(size(data_grid,1),size(data_grid,2),3);
+	image_hsv(:,:,1)=h; clear h;
+	image_hsv(:,:,2)=s; clear s;
+	image_hsv(:,:,3)=v; clear v;
+	image_rgb=hsv2rgb(image_hsv);
+else
+	colorm = getcolormap(options);
+	len    = size(colorm,1);
+
+	ind = ceil((len-1)*(data_grid-data_min)/(data_max - data_min + eps) +1);
+	ind(find(ind>len))=len;
+	image_rgb=zeros(size(data_grid,1),size(data_grid,2),3);
+	r=colorm(:,1); image_rgb(:,:,1)=r(ind); clear r;
+	g=colorm(:,2); image_rgb(:,:,2)=g(ind); clear g;
+	b=colorm(:,3); image_rgb(:,:,3)=b(ind); clear b;
+
+	%Now add radarmap
+	r = image_rgb(:,:,1).*radar;  r(data_nan) = radar(data_nan);  image_rgb(:,:,1) = r;  clear r;
+	g = image_rgb(:,:,2).*radar;  g(data_nan) = radar(data_nan);  image_rgb(:,:,2) = g;  clear g;
+	b = image_rgb(:,:,3).*radar;  b(data_nan) = radar(data_nan);  image_rgb(:,:,3) = b;  clear b;
+end
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+%Plot: 
+imagesc(md.radaroverlay.x*getfieldvalue(options,'unit',1),md.radaroverlay.y*getfieldvalue(options,'unit',1),image_rgb);set(gca,'YDir','normal');
+
+%last step: mesh overlay?
+if exist(options,'edgecolor'),
+	hold on
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none',...
+		'EdgeColor',getfieldvalue(options,'edgecolor'),'LineWidth',getfieldvalue(options,'linewidth',1));
+end
+
+%Apply options, without colorbar and without grid
+options=changefieldvalue(options,'colormap',colorm);              % We used an HSV colorbar
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'axis','equal off');              % default axis
+applyoptions(md,data,options);
+drawnow
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthist.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthist.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthist.m	(revision 13101)
@@ -0,0 +1,34 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+subplot(2,1,1)
+bar(imin:imax,part(:,1));
+xlim([imin-0.5 imax+0.5])
+title('Number of Nodes in Each Partition')
+
+subplot(2,1,2)
+bar(imin:imax,part(:,2));
+xlim([imin-0.5 imax+0.5])
+title('Total Weight in Each Partition')
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistn.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistn.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistn.m	(revision 13101)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+%bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Total Weight in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistw.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistw.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_parthistw.m	(revision 13101)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+%bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Total Weight in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_penalties.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_penalties.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_penalties.m	(revision 13101)
@@ -0,0 +1,48 @@
+function plot_penalties(md,options,width,i);
+%PLOT_PENALTIES - plot penalties
+%
+%   Usage:
+%      plot_penalties(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh penalties
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if ~md.mesh.dimension==3,
+	error('no penalties to plot for ''2d'' model');
+elseif isempty(md.penalties),
+	disp('no penalty applied in this model');
+	return;
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	hold on;
+	for (i=1:size(md.penalties,1)),
+		P1=plot3(x(md.penalties(i,1)),y(md.penalties(i,1)),z(md.penalties(i,1)),'ro','MarkerSize',15,'MarkerFaceColor','r');
+		P2=plot3(x(md.penalties(i,:)),y(md.penalties(i,:)),z(md.penalties(i,:)),'bo-','LineWidth',2,'MarkerSize',8,'MarkerFaceColor','b');
+	end
+	legend([P1 P2],'MacAyeal''s penalized nodes','Pattyn''s penalized nodes');
+end
+
+%apply options
+options=addfielddefault(options,'title','Penalties');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_profile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_profile.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_profile.m	(revision 13101)
@@ -0,0 +1,55 @@
+function plot_profile(md,data,options,nlines,ncols,ii)
+%PLOT_SECTION - plot a given field on a profile
+%
+%   Usage:
+%      plot_profile(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+if is2d, error('only 3d model supported'); end
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%Get coordinates
+location=getfieldvalue(options,'profile');
+if ~isnumeric(location) | numel(location)~=2,
+	error('location provided not supported (should be [x y])');
+end
+xprof=location(1);
+yprof=location(2);
+
+%Loop over number of curves
+for i=1:numcurves,
+
+	%Process data
+	[datai datatype]=processdata(md,data(:,i),options);
+
+	%resolution
+	if exist(options,'resolution'),
+		resolution=getfieldvalue(options,'resolution');
+	else %Default resolution
+		resolution=[100];
+		disp(['plot_profile warning: no resolution specified, using default: ' num2str(resolution) ]);
+	end
+
+	%Compute profile value
+	[z,data_interp]=ProfileValues(md,datai,xprof,yprof,resolution);
+
+	%plot profile
+	subplot(nlines,ncols,ii)
+	plot(data_interp,z,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1),'LineStyle','-');
+	hold on;
+end
+
+%apply options
+options=addfielddefault(options,'title','Profile');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'ylabel','z');
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmu_mass_flux_segments.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13101)
@@ -0,0 +1,49 @@
+function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%PLOT_QMU_MASS_FLUX_SEGMENTS - plot segments from the qmu analysis of mass fluxes
+%
+%   Usage:
+%      plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%
+
+subplot(nlines,ncols,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+allsegments=md.qmu.mass_flux_segments;
+
+if (md.mesh.dimension==2),
+
+	%recover segments
+	hold on
+	for i=1:length(allsegments),
+		segments=allsegments{i};
+
+		%plot semgnets
+		for j=1:length(segments),
+			plot([segments(j,1) segments(j,3)],[segments(j,2) segments(j,4)]);
+		end
+		text(segments(j,1),segments(j,2),['Profile #' num2str(i)]);
+
+		%plot normals
+		
+		for j=1:length(segments),
+			xstart=mean([segments(j,1) segments(j,3)]);
+			ystart=mean([segments(j,2) segments(j,4)]);
+			length1=sqrt((segments(j,1)-segments(j,3)).^2 + (segments(j,2)-segments(j,4)).^2);
+			normal(:,1)=cos(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			normal(:,2)=sin(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			xend=xstart+length1.*normal(:,1);
+			yend=ystart+length1.*normal(:,2);
+			plot([xstart xend],[ystart yend],'r-');
+		end
+
+	end
+else
+	error('plot_qmu_mass_flux_segments: 3d plot of segments not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Mass Flux segments and normals');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmuhistnorm.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmuhistnorm.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmuhistnorm.m	(revision 13101)
@@ -0,0 +1,48 @@
+function plot_qmuhistnorm(md,options,nlines,ncols,index);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+
+%recover histnorm data
+if ~exist(options,'qmudata')
+	error('plot_qmuhistnorm error message: option qmudata is required');
+else
+	qmudata=getfieldvalue(options,'qmudata');
+end
+
+%process options for the qmu plot: 
+
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%
+
+qmuoptions='';
+
+if exist(options,'hmin'), hmin=getfieldvalue(options,'hmin'); qmuoptions=[qmuoptions ',''hmin'',' num2str(hmin)]; end
+if exist(options,'hmax'), hmax=getfieldvalue(options,'hmax'); qmuoptions=[qmuoptions ',''hmax'',' num2str(hmax)]; end
+if exist(options,'hnint'), hnint=getfieldvalue(options,'hnint'); qmuoptions=[qmuoptions ',''hnint'',' num2str(hnint)]; end
+if exist(options,'ymin1'), ymin1=getfieldvalue(options,'ymin1'); qmuoptions=[qmuoptions ',''ymin1'',' num2str(ymin1)]; end
+if exist(options,'ymax1'), ymax1=getfieldvalue(options,'ymax1'); qmuoptions=[qmuoptions ',''ymax1'',' num2str(ymax1)]; end
+if exist(options,'ymin2'), ymin2=getfieldvalue(options,'ymin2'); qmuoptions=[qmuoptions ',''ymin2'',' num2str(ymin2)]; end
+if exist(options,'ymax2'), ymax2=getfieldvalue(options,'ymax2'); qmuoptions=[qmuoptions ',''ymax2'',' num2str(ymax2)]; end
+if exist(options,'cdfplt'), cdfplt=getfieldvalue(options,'cdfplt'); qmuoptions=[qmuoptions ',''cdfplt'',''' cdfplt '''']; end
+if exist(options,'cdfleg'), cdfleg=getfieldvalue(options,'cdfleg'); qmuoptions=[qmuoptions ',''cdfleg'',''' cdfleg '''']; end
+if exist(options,'nrmplt'), nrmplt=getfieldvalue(options,'nrmplt'); qmuoptions=[qmuoptions ',''nrmplt'',''' nrmplt '''']; end
+if exist(options,'EdgeColor'), EdgeColor=getfieldvalue(options,'EdgeColor'); qmuoptions=[qmuoptions ',''EdgeColor'',''' EdgeColor '''']; end
+if exist(options,'FaceColor'), FaceColor=getfieldvalue(options,'FaceColor'); qmuoptions=[qmuoptions ',''FaceColor'',''' FaceColor '''']; end
+
+%use qmu plot
+eval(['plot_hist_norm(qmudata' qmuoptions ');']);
+
+%apply options
+options=changefieldvalue(options,'colorbar','off');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmumean.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmumean.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmumean.m	(revision 13101)
@@ -0,0 +1,59 @@
+function plot_qmumean(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot mean of a scaled response 
+%
+%   Usage:
+%      plot_qmumean(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmumean error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmumean error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).mean;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Mean distribution of ' descriptor]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmunormplot.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmunormplot.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmunormplot.m	(revision 13101)
@@ -0,0 +1,45 @@
+%
+%  plot a normal probability plot of the response functions.
+%
+%  []=plot_normplot(rfunc)
+%
+function []=plot_qmunormplot(rfunc,width,ii)
+
+if ~nargin
+    help plot_normplot
+    return
+end
+
+%%  assemble the data into a matrix
+
+desc=cell (1,length(rfunc));
+for i=1:length(rfunc)
+    ldata(i)=length(rfunc(i).sample);
+end
+data=zeros(max(ldata),length(rfunc));
+
+for i=1:length(rfunc)
+    desc(i)=cellstr(rfunc(i).descriptor);
+    data(1:ldata(i),i)=rfunc(i).sample;
+end
+
+%standard plot:
+subplot(width,width,ii);
+
+%%  draw the plot
+
+%  draw normal probability plot
+
+normplot(data)
+ax1=gca;
+
+%  add the annotation
+
+title('Normal Probability Plot of Design Variables and/or Response Functions')
+xlabel('Value')
+ylabel('Probability')
+
+hleg1=legend(ax1,desc,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmustddev.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmustddev.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_qmustddev.m	(revision 13101)
@@ -0,0 +1,60 @@
+function plot_qmustddev(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot stddev of a scaled response 
+%
+%   Usage:
+%      plot_qmustddev(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmustddev error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmustddev error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).stddev/allresponses(i).mean*100;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Stddev  distribution of ' descriptor ' in %']);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver.m	(revision 13101)
@@ -0,0 +1,26 @@
+function plot_quiver(x,y,u,v,options),
+%PLOT_QUIVER - quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver(x,y,u,v,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.initialization.vx,md.initialization.vy,options);
+
+%process fields
+[quivers,palette]=quiver_process(x,y,u,v,options);
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+quiver_colorbar(quivers,options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver3.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver3.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_quiver3.m	(revision 13101)
@@ -0,0 +1,104 @@
+function plot_quiver3(x,y,z,u,v,w,options),
+%PLOT_QUIVER3 - 3d quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver3(x,y,z,u,v,w,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.mesh.z,md.initialization.vx,md.initialization.vy,md.initialization.vz,options);
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(z) & ~isnan(u) & ~isnan(v) & ~isnan(w));
+x=x(pos); y=y(pos); z=z(pos);
+u=u(pos); v=v(pos); w=w(pos);
+
+%get norm Min and Max
+Norm=sqrt(u.^2+v.^2+w.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%process options: scaling factor?
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',NaN);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	c=[0 0 1;1 0 0];
+elseif numcolors==3,
+	%blue yellow and red
+	c=[0 0 1;1 1 0;1 0 0];
+else
+	%let jet choose
+	c=colormap(jet(numcolors));
+end
+
+%Scale data
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:numcolors
+	pos=find( (Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	hprime=quiver3(x(pos),y(pos),z(pos),u(pos),v(pos),w(pos),'Color',c(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+if  ~strcmpi(getfieldvalue(options,'colorbar','on'),'off'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(levels));
+	for i=1:length(levels),
+		ticklabel{i}=num2str(round_ice(levels(i),3));
+	end
+	tickpos=1:numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(levels)/10);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_referential.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_referential.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_referential.m	(revision 13101)
@@ -0,0 +1,91 @@
+function plot_referential(md,options,width,i,data);
+%PLOT_PRESSURELOAD - plot segment on neumann BC
+%
+%   Usage:
+%      plot_referential(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+referential=md.diagnostic.referential;
+
+Xhat=md.diagnostic.referential(:,1:3);
+pos=find(sum(isnan(Xhat),2));
+Xhat(pos,:)=repmat([1 0 0],size(pos,1),1);
+Xhatnorm=sqrt(Xhat(:,1).^2+Xhat(:,2).^2+Xhat(:,3).^2);
+Xhat=Xhat./[Xhatnorm Xhatnorm Xhatnorm];
+
+Zhat=md.diagnostic.referential(:,4:6);
+pos=find(sum(isnan(Zhat),2));
+Zhat(pos,:)=repmat([0 0 1],size(pos,1),1);
+Zhatnorm=sqrt(Zhat(:,1).^2+Zhat(:,2).^2+Zhat(:,3).^2);
+Zhat=Zhat./[Zhatnorm Zhatnorm Zhatnorm];
+
+Yhat=cross(Zhat,Xhat);
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	len=min(edgex)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	hx=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	hy=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','red','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy],'local X direction','local Y direction')
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	edgez=max(md.mesh.z(elements),[],2)-min(md.mesh.z(elements),[],2);
+	len=min(edgex)/1.5;
+	lenz=min(edgez)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	zend=zstart+len*Xhat(:,3);
+	hx=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	zend=zstart+len*Yhat(:,3);
+	hy=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','red','ShowArrowHead','on','AutoScale','off');
+	%plot Z axis
+	xend=xstart+lenz*Zhat(:,1);
+	yend=ystart+lenz*Zhat(:,2);
+	zend=zstart+lenz*Zhat(:,3);
+	hz=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','green','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy,hz],'local X direction','local Y direction','local Z direction')
+end
+
+%apply options
+options=addfielddefault(options,'title','Diagnostic referential');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftfraction.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftfraction.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftfraction.m	(revision 13101)
@@ -0,0 +1,48 @@
+function plot_riftfraction(md,options,nlines,ncols,index);
+%PLOT_RIFTFRACTION - plot rift fractions
+%
+%   Usage:
+%      plot_riftfraction(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%check that there is something in riftproperties
+if isnan(md.rifts.riftstruct.riftproperties),
+	error('plot_riftfraction error message: field riftproperies is empty, run the model first')
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%first, build a vector of fractions, over all nodes. 
+fractions=zeros(md.mesh.numberofvertices,1);
+
+%complete the tips.
+for i=1:length(md.rifts.riftstruct), 
+	tips=md.rifts.riftstruct(i).tips;
+	fractions(tips)=1;
+end
+
+hold on;
+for i=1:length(md.rifts.riftstruct), 
+	segments=md.rifts.riftstruct(i).segments(:,1:2)';
+	xc=x(segments(:));
+	yc=y(segments(:));
+	zc=fractions(segments(:));
+	h2=patch('Xdata',xc,'Ydata',yc,'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat');
+end
+legend([h1,h2],'mesh boundaries','rifts')
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift ice/water fraction ???????'); %Eric, could you enter a better title?
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftnumbering.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftnumbering.m	(revision 13101)
@@ -0,0 +1,94 @@
+function plot_riftnumbering(md,options,nlines,ncols,index);
+%PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
+%
+%   Usage:
+%      plot_riftnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+fontsize=getfieldvalue(options,'FontSize',8);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+
+%Now, plot rift vertices numbers.
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	for j=1:size(penaltypairs,1),
+		node=penaltypairs(j,1);
+		t=text(x(node),y(node),[num2str(i) '.' num2str(j)]);
+		set(t,'FontSize',fontsize);
+	end
+end
+
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftpenetration.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftpenetration.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftpenetration.m	(revision 13101)
@@ -0,0 +1,82 @@
+function plot_rifpenetration(md,options,nlines,ncols,index);
+%PLOT_RIFTPENETRATION - plot rift penetration
+%
+%   Usage:
+%      plot_rifpenetration(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftrelvel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftrelvel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftrelvel.m	(revision 13101)
@@ -0,0 +1,115 @@
+function plot_riftrelvel(md,options,nlines,ncols,index);
+%PLOT_RIFTRELVEL - plot rift relative velocities
+%
+%   Usage:
+%      plot_riftrelvel(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%recover vx and vy:
+vx=getfieldvalue(options,'riftrelvel_vx',md.initialization.vx);
+vy=getfieldvalue(options,'riftrelvel_vy',md.initialization.vy);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(md.rifts.riftstruct(i).penaltypairs(:,1))=vx(penaltypairs(:,1))-vx(penaltypairs(:,2));
+	v(md.rifts.riftstruct(i).penaltypairs(:,1))=vy(penaltypairs(:,1))-vy(penaltypairs(:,2));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	hprime=quiver(quivers.x(pos),quivers.y(pos),-quivers.u(pos),-quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+for i=1:size(md.rifts.riftstruct,1),
+	
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'k-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=vx(penaltypairs(j,1)); vx2=vx(penaltypairs(j,2)); vy1=vy(penaltypairs(j,1)); vy2=vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+%legend
+if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+	if isp1 & isp2
+		l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+	elseif isp1
+		l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+	elseif isp2
+		l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+	else
+		l=legend([h1,h2],'mesh boundaries','crack tips');
+	end
+set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift/Fault Relative Velocity');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_rifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_rifts.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_rifts.m	(revision 13101)
@@ -0,0 +1,77 @@
+function plot_rifts(md,options,nlines,ncols,index);
+%PLOT_RIFTS - plot rifts in a mesh
+%
+%   Usage:
+%      plot_rifts(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,index); 
+
+%offset to separate rift flanks.
+offset=getfieldvalue(options,'offset',500);
+if isstruct(md.rifts.riftstruct),
+	
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+			x(penaltypairs(j,1))=x(penaltypairs(j,1))-normal(1)*offset;
+			y(penaltypairs(j,1))=y(penaltypairs(j,1))-normal(2)*offset;
+		end
+		if length(md.rifts.riftstruct(i).tips)==3,
+			tip=md.rifts.riftstruct(i).tips(3);
+			%who is tip connected to? 
+			if isconnected(md.mesh.elements,penaltypairs(1,1),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+
+			if isconnected(md.mesh.elements,penaltypairs(1,2),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,1),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,2),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+		end
+	end
+end
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+else
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+end
+
+%apply options
+options=addfielddefault(options,'title','Rifts');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftvel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftvel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_riftvel.m	(revision 13101)
@@ -0,0 +1,108 @@
+function plot_riftvel(md,options,nlines,ncols,index);
+%PLOT_RIFTVEL - plot rift velocity
+%
+%   Usage:
+%      plot_riftvel(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(penaltypairs(:))=md.initialization.vx(penaltypairs(:));
+	v(penaltypairs(:))=md.initialization.vy(penaltypairs(:));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+
+for i=1:size(md.rifts.riftstruct,1),
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=md.initialization.vx(penaltypairs(j,1)); vx2=md.initialization.vx(penaltypairs(j,2)); vy1=md.initialization.vy(penaltypairs(j,1)); vy2=md.initialization.vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+
+
+%legend
+if isp1 & isp2
+	legend([h1,h2,p1,p2],'mesh boundaries','rift tips',' rifts closing','rifts opening')
+elseif isp1
+	legend([h1,h2,p1],'mesh boundaries','rift tips',' rifts closing')
+elseif isp2
+	legend([h1,h2,p2],'mesh boundaries','rift tips','rifts opening')
+else
+	legend([h1,h2],'mesh boundaries','rift tips')
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift Velocities');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_sarpwr.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_sarpwr.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_sarpwr.m	(revision 13101)
@@ -0,0 +1,26 @@
+function plot_sarpwr(md,options,width,i);
+%PLOT_SARPWR - plot radar image
+%
+%   Usage:
+%      plot_sarpwr(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh sarpwr
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	md.mesh.x=md.mesh.x*unit;
+	md.mesh.y=md.mesh.y*unit;
+	md.mesh.z=md.mesh.z*unit;
+end
+					
+imagesc(md.radaroverlay.x,md.radaroverlay.y,double(md.radaroverlay.pwr)),set(gca,'YDir','normal');colormap(gray);
+
+%apply options
+options=addfielddefault(options,'colorbar',0);
+options=changefieldvalue(options,'colormap','gray');
+
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_scatter.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_scatter.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_scatter.m	(revision 13101)
@@ -0,0 +1,74 @@
+function plot_scatter(x,y,mksize,level),
+
+%check input
+if numel(x)~=numel(y) | numel(x)~=numel(level),
+	error('x, y and data should have the same size');
+end
+
+%Some processing
+Min=min(level);
+Max=max(level);
+Siz=length(level);
+nlab=10;
+
+%OK, should we create a new colorbar for the occasion?
+if isempty(findobj(gcf,'tag','TMW_COLORBAR')),
+	alreadyplot=false;
+else
+	alreadyplot=true;
+end
+
+%generate levels
+if (alreadyplot),
+	phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
+	h    = phch{1};
+	ylim=get(h,'YLim');
+	palette=colormap;
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(ylim(1),ylim(2),numcolors+1),2);
+else
+	numcolors=30;
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+	palette=colormap(jet(numcolors));
+end
+
+colorind=ones(Siz,1);
+for i=1:numcolors
+	pos=find((level>=levels(i)) & (level<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(level>levels(end)))=numcolors;
+
+%loop over the number of colors
+hold on
+hp=[];
+for i=1:numcolors
+	pos=find(colorind==i);
+	hprime=plot(x(pos),y(pos),...
+		'o','MarkerSize',mksize,'MarkerEdgeColor',palette(i,:),...
+		'MarkerFaceColor',palette(i,:));
+	hp=[hp;hprime];
+end
+
+if ~alreadyplot,
+	% format the colorbar
+	h    = colorbar;
+	nlab = abs(nlab);                       % number of labels must be positive
+	set(h,'YLim',[1 numcolors]);                  % set colorbar limits
+	set(h,'YTick',linspace(1,numcolors,nlab));    % set tick mark locations
+
+	labels = cell(1,nlab);
+	tick_vals = linspace(Min,Max,nlab);
+	warning off MATLAB:log:logOfZero;
+	for i = 1:nlab
+		if min(log10(abs(tick_vals))) <= 3, fm = '%-4.0f';   % fixed
+		else                                fm = '%-4.0E';   % floating
+		end
+		labels{i} = sprintf(fm,tick_vals(i));
+	end
+	warning on MATLAB:log:logOfZero;
+
+	% set tick label strings
+	set(h,'YTickLabel',labels);
+	%colorbar %one last time required sometimes
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_section.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_section.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_section.m	(revision 13101)
@@ -0,0 +1,210 @@
+function plot_section(md,data,options,nlines,ncols,i)
+%PLOT_SECTION - plot a given field on a section
+%
+%   Usage:
+%      plot_section(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%How many subplots?
+if exist(options,'showsection')
+
+	%Compute the indexes of the 2 plots (one for the sectionvalue and one for showsection
+	upperplots=floor((i-1)/ncols);
+	if upperplots==0, leftplots=i-1; else leftplots=i-ncols*upperplots-1; end
+	index1=4*ncols*upperplots+2*leftplots+1;
+	index2=index1+1;
+	ncols=2*ncols;
+else
+	index1=i;
+end
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%replug x and y onto model so that SectionValue treats the problem correctly
+md3d=md;
+if exist(options,'layer')
+	md.mesh.x=md.mesh.x2d; md.mesh.y=md.mesh.y2d; md.mesh.elements=md.mesh.elements2d; md.mesh.dimension=2;
+end
+
+%read contours: 
+profiles=expread(getfieldvalue(options,'sectionvalue'));
+numprofiles=length(profiles);
+
+%Loop over number of profiles: 
+for profile_i=1:numprofiles,
+	profile=profiles(profile_i);
+
+	%Loop over number of curves
+	for i=1:numcurves,
+
+		[datai datatype]=processdata(md3d,data(:,i),options);
+
+		%resolution
+		if exist(options,'resolution'),
+			resolution=getfieldvalue(options,'resolution');
+		else %Default resolution
+			resolution=[1000 10*md.mesh.numberoflayers];
+			disp(['plot_section warning: no resolution specified, use default resolution: [horizontal_resolution vertical_resolution]=[' num2str(resolution)  ']']);
+		end
+
+		%Compute section value
+		[elements,x,y,z,s,data_s]=SectionValues(md,datai,profile,resolution);
+
+		%units
+		if exist(options,'unit'),
+			unit=getfieldvalue(options,'unit');
+			x=x*unit;
+			y=y*unit;
+			z=z*unit;
+			s=s*unit;
+		end
+
+		%2D
+		if is2d,
+%		%plot section value
+%		hold on;
+%		subplot(nlines,ncols,index1)
+%		%subplot(1,3,[2 3])
+%		plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+%		%3D
+%	else
+%		%plot section value
+%		%if user requested view2: 2d plot with curvilinear coordinate
+%		if (getfieldvalue(options,'view',3)==2 )
+
+			%Show Section if requested by user
+			if exist(options,'showsection')
+
+				%compute number of labels
+				numlabels=min(getfieldvalue(options,'showsection'),length(s));
+				shift=fix(length(s)/numlabels);
+
+				%plot labels on current graph
+				hold on
+				text(s(1),data_s(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(s(1+(i-1)*shift),data_s(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(s(end),data_s(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+				%plot section only with labels
+				subplot(nlines,ncols,index2)
+				plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,isplanet,datatype,options)
+				hold on
+				text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+				plot(x,y,'-r')
+				axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+				view(2)
+			end
+
+			%plot section value
+			if(i==1), subplot(nlines,ncols,index1); end
+			plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+			hold on
+
+
+			%3D
+		else
+			%plot section value
+			%if user requested view2: 2d plot with curvilinear coordinate
+			if (getfieldvalue(options,'view',3)==2 )
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(s)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(s(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(s(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(s(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [s z zeros(length(s),1)],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+
+			else
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(x)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(x(1),y(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data,is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [x y z],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+				view(3)
+
+			end
+		end
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Section value');
+if (md.mesh.dimension==2)
+	options=addfielddefault(options,'colorbar',0);
+end
+if ((md.mesh.dimension==2) | getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'xlabel','Curvilinear coordinate');
+	options=addfielddefault(options,'axis','auto');
+end
+if (md.mesh.dimension==3 & getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'ylabel','z');
+end
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_segments.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_segments.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_segments.m	(revision 13101)
@@ -0,0 +1,57 @@
+function plot_segments(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_segments(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+segments=md.mesh.segments;
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=segments(:,end);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	if strcmpi(getfieldvalue(options,'segmentnumbering','off'),'on'),
+		text(sum(x(segments(:,1:2)),2)/2,sum(y(segments(:,1:2)),2)/2,sum(z(segments(:,1:2)),2)/2+1,...
+			num2str(md.mesh.segmentmarkers),...
+			'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+	end
+
+	%display arrows pointing outward
+	xstart=mean(x(segments(:,1:end-1)),2);
+	ystart=mean(y(segments(:,1:end-1)),2);
+	length=sqrt((x(segments(:,1))-x(segments(:,2))).^2 + (y(segments(:,1))-y(segments(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	normal(:,2)=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h3=plot(xstart,ystart,'r*');
+
+
+else
+	error('plot_segments: 3d plot of segments not supported yet!');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,q],'element on segment','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Segment boundaries');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_streamlines.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_streamlines.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_streamlines.m	(revision 13101)
@@ -0,0 +1,41 @@
+function plot_streamlines(md,options)
+%PLOT_STREAMLINES - plot stream lines on a figure
+%
+%   Usage:
+%      plot_streamlines(md,options)
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+[u datatype]=processdata(md,md.initialization.vx,options);
+[v datatype]=processdata(md,md.initialization.vy,options);
+
+%some checks
+if ~is2d,
+	disp('plot_streamlines error: streamlines option not supported for 3d plots. Project on a layer')
+	return
+end
+
+%initialize flowpath
+streamlines=getfieldvalue(options,'streamlines');
+if ischar(streamlines) & strcmpi(streamlines,'on');
+	streamlines=60;
+end
+if iscell(streamlines)
+	x0=[]; y0=[];
+	for i=1:size(streamlines,2)
+		coord=streamlines{i};
+		x0=[x0;coord(1)]; y0=[y0;coord(2)];
+	end
+else
+	x0=x(1:ceil(length(x)/streamlines):end);
+	y0=y(1:ceil(length(x)/streamlines):end);
+end
+
+%Get flow lines
+flowpath=flowlines(index,x,y,u,v,x0,y0);
+
+%plot
+hold on
+for i=1:length(flowpath)
+	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor','y');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor.m	(revision 13101)
@@ -0,0 +1,40 @@
+function plot_tensor(md,options,width,i,type);
+%PLOT_TENSOR - plot tensor components
+%
+%   Usage:
+%      plot_tensor(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+h=subplot(width,width,i); axis off; pos=get(h,'Position');
+
+plot_options.offsetx=pos(1);
+plot_options.offsety=pos(2);
+plot_options.width=pos(3);
+plot_options.height=pos(4);
+
+%Figure out tensor type:
+%FIXME does not work anymore
+if strncmpi(type,'strain',6),
+	tensor=md.results.strainrate;
+elseif strncmpi(type,'stress',6),
+	tensor=md.results.stress;
+elseif strncmpi(type,'deviatoricstress',16),
+	tensor=md.results.deviatoricstress;
+else
+	error('plot_tensor error message: unsupported type of tensor');
+end
+
+%Figure out type of plot being requested
+if strncmpi(fliplr(type),fliplr('tensor'),6) | strcmpi(type,'strainrate') | strcmpi(type,'deviatoricstress') | strcmpi(type,'stress'),
+	plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type),fliplr('principal'),9),
+	plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type(1:end-1)),fliplr('principalaxis'),13),
+	plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+	return;
+else
+	error('plot_tensor error message: unsurported type of plot');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_components.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_components.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_components.m	(revision 13101)
@@ -0,0 +1,78 @@
+function plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_COMPONENT - plot component of a tensor
+%
+%   Usage:
+%      plot_tensor_components(md,options,width,i,tensor,type,plot_option);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.xx datatype]=processdata(md,tensor.xx,options);
+[tensor.yy datatype]=processdata(md,tensor.yy,options);
+[tensor.xy datatype]=processdata(md,tensor.xy,options);
+if  md.mesh.dimension==3
+	[tensor.xz datatype]=processdata(md,tensor.xz,options);
+	[tensor.yz datatype]=processdata(md,tensor.yz,options);
+	[tensor.zz datatype]=processdata(md,tensor.zz,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(2*width,2*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(2*width,2*width,index3),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+else
+	subplot(3*width,3*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(3*width,3*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(3*width,3*width,index3),
+	plot_unit(x,y,z,elements,tensor.zz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'zz')
+	subplot(3*width,3*width,index4),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+	subplot(3*width,3*width,index5),
+	plot_unit(x,y,z,elements,tensor.xz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xz')
+	subplot(3*width,3*width,index6),
+	plot_unit(x,y,z,elements,tensor.yz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yz')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+	%apply options
+	if ismember('_',type) %user plotet stress_tensor
+		strings=strsplit(type,'_');
+		string=strings{1};
+	else %default plot: user requested stress
+		string=type;
+	end
+	options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+	applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principal.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principal.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principal.m	(revision 13101)
@@ -0,0 +1,77 @@
+function plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPAL - plot principal values
+%
+%   Usage:
+%      plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+	index4=index3+1;
+	newwidth=2*width;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+	newwidth=3*width;
+end
+
+%plot principal axis
+type1=[type 'axis1'];
+plot_tensor_principalaxis(md,options,newwidth,index1,tensor,type1,plot_options);
+type2=[type 'axis2'];
+plot_tensor_principalaxis(md,options,newwidth,index2,tensor,type2,plot_options);
+if  md.mesh.dimension==3
+	type3=[type 'axis3'];
+	plot_tensor_principalaxis(md,options,newwidth,index3,tensor,type3,plot_options);
+end
+
+%now plot principal values
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.principalvalue1 datatype]=processdata(md,tensor.principalvalue1,options);
+[tensor.principalvalue2 datatype]=processdata(md,tensor.principalvalue2,options);
+if  md.mesh.dimension==3
+	[tensor.principalvalue3 datatype]=processdata(md,tensor.principalvalue3,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index3)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(2*width,2*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+else
+	subplot(3*width,3*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(3*width,3*width,index5)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+	subplot(3*width,3*width,index6)
+	plot_unit(x,y,z,elements,tensor.principalvalue3,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 3')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+%apply options
+if ismember('_',type) %user plotet stress_tensor
+	strings=strsplit(type,'_');
+	string=strings{1};
+else %default plot: user requested stress
+	string=type;
+end
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+options=changefieldvalue(options,'colorbar',2);
+applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principalaxis.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_tensor_principalaxis.m	(revision 13101)
@@ -0,0 +1,95 @@
+function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
+%
+%   Usage:
+%      plot_tensor_principalaxis(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%prepare subplot
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+if ((md.mesh.dimension==2)),
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2);'])
+	eval(['value=tensor.principalvalue' type(end) ';']);
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[value datatype]=processdata(md,value,options);
+else
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2); Vz=tensor.principalaxis' type(end) '(:,3);'])
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[Vz datatype]=processdata(md,Vz,options);
+	[value datatype]=processdata(md,value,options);
+end
+
+%take the center of each element if ~isonnode
+if datatype==1,
+	x=mean(md.mesh.x(md.mesh.elements'))'; y=mean(md.mesh.y(md.mesh.elements'))'; z=mean(md.mesh.z(md.mesh.elements'))';
+end
+
+%plot quivers
+if (md.mesh.dimension==2),
+
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy;
+
+	pos=find(value>=0);
+	q1=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+
+else
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		z=z(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		Vz=Vz(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy; Vz=scale*Vz;
+
+	pos=find(value>=0);
+	q1=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+end
+
+%legend
+if strcmpi(type(1:6),'strain')
+	legend([q1 q2],'extension','compression')
+elseif strcmpi(type(1:6),'stress')
+	legend([q1 q2],'compression','traction')
+end
+
+%apply options
+strings=strsplit(type,'_');
+string=strings{1};
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' principal axis ' type(end)]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_thermaltransient_results.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_thermaltransient_results.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_thermaltransient_results.m	(revision 13101)
@@ -0,0 +1,24 @@
+function plot_thermaltransient_results(md,options,width,i)
+%PLOT_THERMALTRANSIENT_RESULTS - plot  results of a thermal transient solution
+%
+%   Usage:
+%      plot_thermaltransient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+string='plot(md';
+for i=1:length(md.thermaltransient_results),
+	string=[string ',''data'',''thermaltransient_results(' num2str(i) ').temperature'',''view'',3,''title'',''Temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
+string='plot(md';
+for i=2:length(md.thermaltransient_results),
+	string=[string ',''data'',md.thermaltransient_results(' num2str(i) ').temperature-md.thermaltransient_results(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_field.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_field.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_field.m	(revision 13101)
@@ -0,0 +1,43 @@
+function plot_transient_field(md,options,width,i,data)
+%PLOT_TRANSIENT_FIELD - plot transient results
+%
+%   Usage:
+%      plot_transient_field(md,options,width,i,data);
+%
+%   See also: PLOTMODEL
+
+%Check that they are transient results
+if (~isfield(md.results,'TransientSolution')),
+	error('plot_transient_field error message: no transient results in the model');
+end
+
+%Figure out the iterations to plot and check if it is possible
+transient=md.results.TransientSolution;
+maxiteration=size(transient,2);
+steps=getfieldvalue(options,'steps',1:1:maxiteration);
+
+if max(steps)>maxiteration | min(steps)<1,
+	error(['plot_transient_field error message: problem with the steps requested, must be an interger between 0 and ' num2str(maxiteration)]);
+end
+subplotwidth=ceil(sqrt(length(steps)));
+
+%Figure out the field to plot
+
+field=getfieldvalue(options,'field','Vel');
+
+%process mes only once
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot data for all steps
+for i=1:length(steps),
+
+	%process data and change title if needed
+	[data datatype]=processdata(md,transient(steps(i)).(field),options);
+	options=changefieldvalue(options,'title',[field ' at time ' num2str(transient(steps(i)).time/md.constants.yts) ' a']);
+
+	%create plot of step i
+	subplot(subplotwidth,subplotwidth,i);
+	plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+	applyoptions(md,data,options);
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_movie.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_movie.m	(revision 13101)
@@ -0,0 +1,70 @@
+function plot_transient_movie(md,options,width,i);
+%PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
+%   Usage:
+%      plot_transient_movie(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+	%prepare subplot
+	subplot(width,width,i); 
+
+	%xlim
+	if exist(options,'transient_movie_field'),
+		field=getfieldvalue(options,'transient_movie_field');
+	else
+		error('specify transient_movie_field in options list');
+	end
+
+	results=md.results.TransientSolution;
+	%loop over the time steps
+	if exist(options,'transient_movie_limit'),
+		limit=getfieldvalue(options,'transient_movie_limit');
+		steps=[limit(1):limit(end)];
+	else
+		steps=1:length(results);
+	end
+	results=md.results.TransientSolution;
+	nstep=1;
+	for i=steps
+
+		if ~isempty(results(i).(field)),
+			%process data
+			[x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
+			[data datatype]=processdata(md,results(i).(field),options);
+
+			titlestring=[field ' at time ' num2str(results(i).time/md.constants.yts) ' year'];
+			plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+			apply_options_movie(md,options,titlestring);
+
+			if exist(options,'transient_movie_output'),
+				set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+				if nstep==1,
+					%initialize images and frame
+					frame=getframe(gcf);
+					[images,map]=rgb2ind(frame.cdata,256,'nodither');
+					images(1,1,1,length(steps))=0;
+				else
+					frame=getframe(gcf);
+					images(:,:,1,nstep) = rgb2ind(frame.cdata,map,'nodither');
+				end
+			else
+				pause(0.1)
+			end
+			nstep=nstep+1;
+		end
+	end
+
+	%output movie if requested.
+	if exist(options,'transient_movie_output'),
+		filename=getfieldvalue(options,'transient_movie_output');
+		imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',2),'LoopCount',inf)
+	end
+
+end %function
+
+function apply_options_movie(md,options,titlestring)
+	%apply options
+	options=addfielddefault(options,'title',titlestring);
+	options=addfielddefault(options,'colorbar',1);
+	applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_results.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_results.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_transient_results.m	(revision 13101)
@@ -0,0 +1,77 @@
+function plot_transient_results(md,options,width,i)
+%PLOT_TRANSIENT_RESULTS - plot transient results
+%
+%   Usage:
+%      plot_transient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+fontsize=getfieldvalue(options,'fontsize',14);
+fontweight=getfieldvalue(options,'fontweight','n');
+
+%Prepare window distribution
+%Get screen geometry
+mp = get(0, 'MonitorPositions');
+%Build window sizes
+if size(mp,1)>=2        %several monitors, use the second one
+	bdwidth=mp(2,1)+5; topbdwidth=mp(2,2)+20; W=mp(2,3)/3; H=mp(2,4)/2;
+else                    %only one monitor
+	bdwidth=5;         topbdwidth=20;         W=mp(1,3)/3; H=mp(1,4)/2;
+end
+pos1=[bdwidth  H+bdwidth  W-2*bdwidth  H-bdwidth-topbdwidth];
+pos2=pos1+[W 0 0 0]; pos3=pos1+[2*W 0 0 0]; pos4=pos1+[0 -H 0 0]; pos5=pos1+[W -H 0 0]; pos6=pos1+[2*W -H 0 0];
+%Create windows
+figure(1);close;
+figure('Position',pos1); figure('Position',pos2);figure('Position',pos3);figure('Position',pos4);figure('Position',pos5);figure('Position',pos6);
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness,''title'',''Thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel,''view'',3,''title'',''Velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=1:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature,''view'',3,''title'',''Temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',3,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness-md.results.transient(' num2str(i-1) ').thickness,''title'',''Delta thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',4,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel-md.results.transient(' num2str(i-1) ').vel,''view'',3,''title'',''Delta velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',5,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=2:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature-md.results.transient(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',6,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_unit.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_unit.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_unit.m	(revision 13101)
@@ -0,0 +1,92 @@
+function plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+%PLOT_UNIT - unit plot, display data
+%
+%   Usage:
+%      plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options);
+%
+%   See also: PLOTMODEL, PLOT_MANAGER
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+switch datatype,
+
+	%element plot
+	case 1,
+
+		pos=find(~isnan(data)); %needed for element on water
+		if is2d,
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	%node plot
+	case 2,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			if ~isplanet,
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+				patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			else
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+				if size(elements,2)==4, D=elements(:,4); else D=C; end
+				patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			end
+		end
+
+	%quiver plot
+	case 3,
+
+		if is2d,
+			plot_quiver(x,y,data(:,1),data(:,2),options);
+		else
+			plot_quiver3(x,y,z,data(:,1),data(:,2),data(:,3),options);
+		end
+
+	%Patch plot P1
+	case 4,
+
+		if is2d,
+			patch( 'Faces',elements,'Vertices',[x y],'CData',data,'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+		end
+
+	%Patch plot P0
+	case 5,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(:),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	otherwise,
+		error(['case ' num2str(datatype) ' not supported']);
+
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plot_vertexnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plot_vertexnumbering.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plot_vertexnumbering.m	(revision 13101)
@@ -0,0 +1,51 @@
+function plot_vertexnumbering(md,options,width,i);
+%PLOT_VERTEXNUMBERING - plot vertex numbering
+%
+%   Usage:
+%      plot_vertexnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vertexnumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Node numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plotdoc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plotdoc.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plotdoc.m	(revision 13101)
@@ -0,0 +1,174 @@
+function plotdoc()
+%PLOTDOC - plot documentation
+%
+%   Usage:
+%      plotdoc()
+
+disp(' ');
+disp('   Plot usage: plotm(model,varargin)');
+disp('   Options: ');
+disp('       ''figure'': figure number');
+disp('       ''data'' : what we want to plot');
+disp('                Available values for ''data'' are: ');
+disp('                  - any field of the model structure. ex: plot(md,''data'',''vel''), or plot(md,''data'',md.initialization.vel)');
+disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa)');
+disp('                  - ''basal_dragx'' or ''basal_dragy'' : plot a component of the basal drag on the bed (in kPa)');
+disp('                  - ''boundaries'': this will draw all the segment boundaries to the model, including rifts.');
+disp('                  - ''icefront'': this will show segments that are used to define the icefront of the model (Neumann boundary conditions).');
+disp('                  - ''BC'': this will draw all the boundary conditions (Dirichlet and Neumann).');
+disp('                  - ''deviatoricstress_tensor'': plot the components of the deviatoric stress tensor (tauxx,tauyy,tauzz,tauxy,tauxz,tauyz) if computed');
+disp('                  - ''deviatoricstress_principal'': plot the deviatoricstress tensor principal axis and principal values');
+disp('                  - ''deviatoricstress_principalaxis1'': arrow plot the first principal axis of the deviatoricstress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''driving_stress'': plot the driving stress (in kPa)');
+disp('                  - ''elements_type'': model used for each element');
+disp('                  - ''elementnumbering'': numbering of elements');
+disp('                  - ''vertexnumbering'': numbering of vertices');
+disp('                  - ''highlightelements'': to highlight elements to highlight the element list');
+disp('                  - ''highlightvertices'': to highlight vertices (use highlight option to enter the vertex list');
+disp('                  - ''mesh'': draw mesh using trisurf');
+disp('                  - ''referential'': diagnostic referential');
+disp('                  - ''riftvel'': velocities along rifts');
+disp('                  - ''riftrelvel'': relative velocities along rifts');
+disp('                  - ''riftpenetration'': penetration levels for a fault');
+disp('                  - ''riftfraction'': fill fractions for every node of the rifts');
+disp('                  - ''rifts'': plot mesh with an offset so that rifts are visible');
+disp('                  - ''strainrate_tensor'': plot the components of the strainrate tensor (exx,eyy,ezz,exy,exz,eyz) if computed');
+disp('                  - ''strainrate_principal'': plot the strainrate tensor principal axis and principal values)');
+disp('                  - ''strainrate_principalaxis1'': arrow plot the first principal axis of the strainrate tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''stress_tensor'': plot the components of stress tensor (sxx,syy,szz,sxy,sxz,syz) if computed');
+disp('                  - ''stress_principal'': plot the stress tensor principal axis and principal values');
+disp('                  - ''stress_principalaxis1'': arrow plot the first principal axis of the stress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''transient_results'': this will display all the time steps of a transient run (use steps to specify the steps requested)');
+disp('                  - ''transient_vel'': this will display the velocity for the time steps requested in ''steps'' of a transient run');
+disp('                  - ''transient_vel'': vel can be by any field of the transient results (vx, vy, vz, vel, temperature, melting, pressure, bed, thickness, surface)');
+disp('                  - ''transient_field'': dynamic plot of results. specify ''steps'' option, as fell as ''field'' (defaults are all steps, for ''Vel'' field)');
+disp('                  - ''transient_movie'': this will display the time steps of a given field of a transient run');
+disp('                  - ''transient_movie_field'': field to be displayed when doing  transient_movie data display');
+disp('                  - ''transient_movie_output'': filename if output is desired for movie');
+disp('                  - ''transient_movie_time'': time for each image (default 2 seconds)');
+disp('                  - ''thermaltransient_results'': this will display all the time steps of a thermal transient run');
+disp('                  - ''qmuhistnorm'': histogram normal distribution. needs option qmudata');
+disp('                  - ''qmumean'': plot of mean distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''qmustddev'': plot of stddev distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''part_hist'': partitioning node and area histogram');
+disp('                  - ''quiver'': quiver plot');
+
+disp('       ''alloptions'': apply the options to all subplots if ''on''');
+disp('       ''axis'': same as standard matlab option (''equal'',''off'',''equal on'',...)');
+disp('       ''basin'': zoom on a given basin (''pineislandglacier'',''ronneiceshelf'', use isbasin to identify a basin');
+disp('                 ''hemisphere'': specify +1 or -1');
+disp('                 ''basindeltax'': in m');
+disp('                 ''showbasins'': write lables for every existing basin name around the center of the plot');
+disp('       ''caxis'': modify  colorbar range. (array of type [a b] where b>=a)');
+disp('       ''backgroundcolor'': plot background color. (default is ''w'')');
+disp('       ''figurebackgroundcolor'': figure background color. (default is ''none'')');
+disp('       ''coord'':  ''xy'' (default) or ''latlon''');
+disp('       ''colorlevels'':  N or {value1,valu2,value3,...} used if quiver, use different colors for the given number of colors or limits');
+disp('       ''colorbar'': add colorbar (string ''on'' or ''off'')');
+disp('       ''colorbartitle'': colorbar title (string)');
+disp('       ''colorbarYlabel'': colorbar Y label (string)');
+disp('       ''colorbarpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''colorbarcornerposition'': ''West'',''North'',etc ...');
+disp('       ''colorbartitlerotation'': -90, etc ...');
+disp('       ''colorbarfontsize'': specify colorbar fontsize');
+disp('       ''colorbarwidth'': multiplier (default 1) to the default width colorbar');
+disp('       ''colorbarheight'': multiplier (default 1) to the default height colorbar');
+disp('       ''colormap'': same as standard matlab option (''jet'',''hsv'',''cool'',''spring'',''gray'',''Ala'',''Rignot'',...)');
+disp('       ''contourlevels'': N or {value1,valu2,value3,...} add the contours of the specified values or N contours');
+disp('       ''contourticks'': ''on'' or ''off'' to display the ticks of the contours');
+disp('       ''contouronly'': ''on'' or ''off'' to display the contours on a white background');
+disp('       ''contourcolor'': ticks and contour color');
+disp('       ''density'': density of quivers (one arrow every N nodes, N integer)');
+disp('       ''inset'': add an inset (zoom) of the current figure if 1 (use ''insetx'', ''insety'' and ''insetpos'' to determine the inset position and content)');
+disp('       ''insetx'': [min(x) max(x)] where min(x) and max(x) are values determining the inset content');
+disp('       ''insety'': [min(y) max(y)] where min(y) and max(y) are values determining the inset content');
+disp('       ''insetpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''streamlines'': N (number of stream lines) or {[x1 y1],...} (coordinates of seed points) add streanlines on current figure');
+disp('       ''edgecolor'': same as standard matlab option EdgeColor (color name: ''black'' or RGB array: [0.5 0.2 0.8])');
+disp('       ''fontsize'': same as standard matlab option (10,14,...)');
+disp('       ''fontweight'': same as standard matlab option (normal: ''n'',bold: ''b'',light: ''l'',demi: ''d'')');
+disp('       ''fontcolor'': same as standard matlab option');
+disp('       ''highlight'': highlights certain nodes or elements when using ''nodenumbering'' or ''elementnumbering'' or ''highlightnodes '' or ''highlightelements'' option');
+disp('       ''resolution'': resolution used by section value (array of type [horizontal_resolution vertical_resolution])');
+disp('                       horizontal_resolution must be in meter, and vertical_resolution a number of layers');
+disp('       ''showsection'': show section used by ''sectionvalue'' (string ''on'' or a number of labels)');
+disp('       ''sectionvalue'': give the value of data on a profile given by an Argus file (string ''Argusfile_name.exp'')');
+disp('       ''profile'': give the value of data along a vertical profile ([xlocation ylocation])');
+disp('       ''smooth'': smooth element data (string ''yes'' or integer)');
+disp('       ''title'': same as standard matlab option');
+disp('       ''view'': same as standard matlab option (ex: 2, 3 or [90 180]');
+disp('       ''xlim'': same as standard matlab option (ex: [0 500])');
+disp('       ''ylim'': same as standard matlab option');
+disp('       ''zlim'': same as standard matlab option');
+disp('       ''xlabel'': same as standard matlab option (ex:''km'')');
+disp('       ''ylabel'': same as standard matlab option');
+disp('       ''xticklabel'': specifiy xticklabel');
+disp('       ''yticklabel'': specifiy yticklabel');
+disp('       ''overlay'': yes or no. This will overlay a radar amplitude image behind');
+disp('       ''overlay_image'': path to overlay image. provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options also');
+disp('       ''contrast'': (default 1) coefficient to add contrast to the radar amplitude image used in overlays');
+disp('       ''highres'': resolution of overlayed radar amplitude image (default is 0, high resolution is 1).');
+disp('       ''hem'': specify hemisphere ''n'' or ''s'' (default is ''s'').');
+disp('       ''alpha'': transparency coefficient (the higher, the more transparent). Default is 1.5');
+disp('       ''scaling'': scaling factor used by quiver plots. Default is 0.4');
+disp('       ''autoscale'': set to ''off'' to have all the quivers with the same size. Default is ''on''');
+disp('       ''expdisp'': plot exp file on top of a data plot. provide exp file as an argument (use a cell of strings if more than one)');
+disp('       ''expstyle'': marker style for expdisp plot (use a cell of strings if more than one)');
+disp('       ''linewidth'': line width for expdisp plot');
+disp('       ''border'': size of display border (in pixels). active only for overlay plots');
+disp('       ''text'': print string, use a cell of strings if more than one');
+disp('       ''textposition'': [x y] position of text, use a cell of strings if more than one');
+disp('       ''textsize'':  same as standard ''FontSize'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textweight'':  same as standard ''FontWeight'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textcolor'':  same as standard ''color'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textrotation'':  same as standard ''Rotation'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''mask'': list of flags of size numberofnodes or numberofelements. Only ''true'' values are plotted ');
+disp('       ''nan'': value assigned to NaNs (convenient when plotting BC)');
+disp('       ''partitionedges'': ''off'' by default. overlay plot of partition edges');
+disp('       ''log'': value of log');
+disp('       ''latlon'': ''on'' or {latstep lonstep [resolution [color]]} where latstep,longstep and resolution are in degrees, color is a [r g b] array');
+disp('       ''latlonnumbering'': ''on'' or {latgap longap colornumber latangle lonangle} where latgap and longap are pixel gaps for the numbers,'); 
+disp('       ''latlonclick'': ''on'' to click on latlon ticks positions');
+disp('                   colornumber is a [r g b] array and latangle and lonangle are angles to flip the numbers');
+disp('       ''northarrow'': add an arrow pointing north, ''on'' for default value or [x0 y0 length [ratio width fontsize]] where (x0,y0) are the coordinates of the base, ratio=headlength/length');
+disp('       ''offset'': mesh offset used by ''rifts'', default is 500');
+disp('       ''scaleruler'': add a scale ruler, ''on'' for default value or [x0 y0 length width numberofticks] where (x0,y0) are the coordinates of the lower left corner');
+disp('       ''showregion'': show domain in Antarctica on an inset, use ''insetpos'' properties');
+disp('       ''visible'': ''off'' to make figure unvisible, default is ''on''');
+disp('       ''wrapping'': repeat ''n'' times the colormap (''n'' must be an integer)');
+disp('       ''unit'': by default, in m, otherwise, ''km'' is available');
+disp('       ''legend_position'': by default, ''NorthEasth''');
+disp('       ''qmudata'': data for qmu  plots.');
+disp('                  {dresp1   ,dresp2  ,hmin,hmax,hnint} or {samp,desc,mu,sigma,hmin,hmax,hnint}');
+disp('                  where dresp1 is a structure array of responses (where we need samp and desc), ');
+disp('                  dresp2 is a structure array of responses (where we only need mu and sigma)');
+disp('                  hmin,hmax and hnint are the minimum, maximum and number of intervals of the histogram (optional)');
+disp('       ''figposition'': position of figure: ''fullscreen'', ''halfright'', ''halfleft'', ''portrait'', ''landscape'',... (hardcoded in applyoptions.m)');
+disp('       ''offsetaxispos'': offset of current axis position to get more space (ex: [-0.02 0  0.04 0])');
+disp('       ''axispos'': axis position to get more space');
+disp('       ''hmin'': (numeric, minimum for histogram)');
+disp('       ''hmax'': (numeric, maximum for histogram)');
+disp('       ''hnint'': (numeric, number of intervals for histogram)');
+disp('       ''ymin1'': (numeric, minimum of histogram y-axis)');
+disp('       ''ymax1'': (numeric, maximum of histogram y-axis)');
+disp('       ''ymin2'': (numeric, minimum of cdf y-axis)');
+disp('       ''ymax2'': (numeric, maximum of cdf y-axis)');
+disp('       ''cdfplt'': (char, ''off'' to turn off cdf line plots)');
+disp('       ''cdfleg'': (char, ''off'' to turn off cdf legends)');
+disp('       ''segmentnumbering'': (''off'' by default)');
+disp('       ''kmlgroundoverlay'': (''off'' by default)');
+disp('       ''kmlfilename'': (''tempfile.kml'' by default)');
+disp('       ''kmlroot'': (''./'' by default)');
+disp('       ''kmlimagename'': (''tempimage'' by default)');
+disp('       ''kmlimagetype'': (''png'' by default)');
+disp('       ''kmlresolution'': (1 by default)');
+disp('       ''kmlfolder'': (''Ground Overlay'' by default)');
+disp('       ''kmlfolderdescription'': ('''' by default)');
+disp('       ''kmlgroundoverlayname'': ('''' by default)');
+disp('       ''kmlgroundoverlaydescription'': ('''' by default)');
+
+disp('       any options (except ''data'') can be followed by ''#i'' where ''i'' is the subplot number, or ''#all'' if applied to all plots');
+disp('  ');
+disp('   Examples:');
+disp('       plotmodel(md,''data'',''vel'',''data'',''mesh'',''view#2'',3,''colorbar#all'',''on'',''axis#1'',''off equal'')');
+disp('       plotmodel(md,''data'',''highlightelements'',''highlight'',[1 4 10],''expdisp'',{''domain1.exp'' ''domain2.exp'' ''domain3.exp''})');
Index: /issm/branches/trunk-jpl-damage/src/m/plot/plotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/plotmodel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/plotmodel.m	(revision 13101)
@@ -0,0 +1,57 @@
+function plotmodel(md,varargin)
+%At command prompt, type plotdoc for help on documentation.
+
+%First process options
+options=plotoptions(varargin{:});
+
+%get number of subplots
+subplotwidth=ceil(sqrt(options.numberofplots));
+
+%if nlines and ncols specified, then bypass.
+if exist(options.list{1},'nlines'),
+	nlines=getfieldvalue(options.list{1},'nlines');
+else 
+	nlines=subplotwidth;
+end
+
+if exist(options.list{1},'ncols'),
+	ncols=getfieldvalue(options.list{1},'ncols');
+else 
+	ncols=subplotwidth;
+end
+
+%check that nlines and ncols were given at the same time!
+if ((exist(options.list{1},'ncols') & ~exist(options.list{1},'ncols')) | (~exist(options.list{1},'ncols') & exist(options.list{1},'ncols')))
+	error('plotmodel error message: nlines and ncols  need to be specified together, or not at all');
+end
+
+%Get figure number and number of plots
+figurenumber=options.figurenumber;
+numberofplots=options.numberofplots;
+
+%go through subplots
+if numberofplots,
+		
+	%Create figure 
+	if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
+		F=figure(figurenumber);clf;
+		set(F,'Visible','Off');
+	else
+		figure(figurenumber);clf;
+	end
+
+	%Use zbuffer renderer (snoother colors)
+	set(gcf,'Renderer','zbuffer');
+
+	%Go through all data plottable and close window if an error occurs
+	try,
+		for i=1:numberofplots,
+			plot_manager(getfieldvalue(options.list{i},'model',md),options.list{i},subplotwidth,nlines,ncols,i);
+		end
+	catch me,
+		%figure(figurenumber),close;
+		rethrow(me);
+	end
+else
+	error('plotmodel error message: no output data found. ');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/processdata.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/processdata.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/processdata.m	(revision 13101)
@@ -0,0 +1,203 @@
+function [data datatype]=processdata(md,data,options);
+%PROCESSDATA - process data to be plotted
+%
+%   datatype = 1 -> elements
+%   datatype = 2 -> nodes
+%   datatype = 3 -> node quivers
+%   datatype = 4 -> patch
+%
+%   Usage:
+%      [data datatype]=processdata(md,data,options);
+%
+%   See also: PLOTMODEL, PROCESSMESH
+
+%check format
+if (iscell(data) | isempty(data) | length(data)==0 | (length(data)==1 & ~isstruct(data) & isnan(data))),
+	error('plotmodel error message: data provided is empty');
+end
+
+%needed later on
+if isfield(md.mesh,'numberofvertices2d'), 
+	numberofvertices2d=md.mesh.numberofvertices2d; 
+	numberofelements2d=md.mesh.numberofelements2d; 
+else 
+	numberofvertices2d=NaN;
+	numberofelements2d=NaN;
+end
+
+%Process Patch
+if isstruct(data) 
+	if (isfield(data,'index') & isfield(data,'value')),
+		if data.interpolation(1)==P1Enum(),
+			data=data.value;
+			data=data';
+			data=data(:);
+			datatype=4;
+		elseif data.interpolation(1)==P0Enum(),
+			data=data.value;
+			datatype=5;
+		else
+			error(['interpolation ' data.interpolation(1) ' not supported yet']);
+		end
+	else
+		error('structure other than Patch not supported yet');
+	end
+else
+	%initialize datatype
+	datatype=0;
+end
+
+%get datatype
+datasize=size(data);
+
+%Process NaN if any (do not now before mask is applied)
+if exist(options,'nan')
+	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+end
+%non patch processing
+if datatype~=4 & datatype~=5,
+
+	%transpose data if necessary
+	if (size(data,2) > size(data,1)),
+		data=data';
+	end
+	datasize=size(data);
+
+	%convert to double if necessary
+	if ~isnumeric(data);
+		disp('processdata info message: data is not numeric (logical?). Converted to double');
+		data=double(data);
+	end
+
+	%check length
+	
+	if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (md.mesh.dimension==3 & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
+		error('plotmodel error message: data not supported yet');
+	end
+	
+	%quiver?
+	if datasize(2)>1,
+		datatype=3;
+
+		%check number of columns, add zeros if necessary,
+		if (md.mesh.dimension==3)
+			if datasize(2)==2,
+				data=[data, zeros(datasize(1),1)];
+			elseif datasize(2)~=3,
+				error('plotmodel error message: data provided should have 2 or 3 columns for quiver plot, and 1 for regular plot');
+			end
+		%elseif ((md.mesh.dimension==2) & datasize(2)~=2),
+		%	error('plotmodel error message: data provided should have 2 columns for quiver plot, and 1 for regular plot');
+		end
+	end
+
+	%treat the case datasize(1)=6*nodes
+	if datasize(1)==6*md.mesh.numberofvertices
+		%keep the only norm of data
+		data1=data(1:6:md.mesh.numberofvertices*6,:);
+		data2=data(2:6:md.mesh.numberofvertices*6,:);
+		data=sqrt(data1.^2+data2.^2);
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==numberofvertices2d),
+		data=project3d(md,'vector',data,'type','node');
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==numberofelements2d),
+		data=project3d(md,'vector',data,'type','element');
+		datasize(1)=md.mesh.numberofelements;
+		%---> go to node data
+	end
+
+	%smoothing?
+	if exist(options,'smooth')
+		data=averaging(md,data,getfieldvalue(options,'smooth'));
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+end
+
+%element data
+if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+
+	%Initialize datatype if non patch
+	if datatype~=4 & datatype~=5,
+		datatype=1;
+	end
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+			data(pos2,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(pos,:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+		data(find(data<bounds(1)))=bounds(1);
+		if any(data<=0),
+			error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		end
+		pos=find(~isnan(data));
+		data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+	end
+end
+
+%node data
+if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+	datatype=2;
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			data(pos,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(md.mesh.elements(pos,:),:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		%if any(data<=0),
+		%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		%end
+		data=log(data)/log(getfieldvalue(options,'log'));
+	end
+end
+
+%layer projection? 
+if getfieldvalue(options,'layer',0)>=1,
+	data=project2d(md,data,getfieldvalue(options,'layer')); %project onto 2d mesh
+end
+
+%control arrow density if quiverplot
+if datatype==3 & exist(options,'density')
+	databak=data;
+	data=NaN*ones(datasize);
+	density=getfieldvalue(options,'density');
+	data(1:density:end,:)=databak(1:density:end,:);
+	clear databak
+end
+
+%OK, if datatype=0 error out
+if datatype==0,
+	error(['data provided not recognized or not supported']);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/processmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/processmesh.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/processmesh.m	(revision 13101)
@@ -0,0 +1,96 @@
+function [x y z elements is2d isplanet]=processmesh(md,data,options);
+%PROCESSMESH - process mesh to be plotted
+%
+%   Usage:
+%      [x y z elements is2d]=processmesh(md,data,options)
+%
+%   See also: PLOTMODEL, PROCESSDATA
+
+%some checks
+if md.mesh.numberofvertices==0,
+	error('plot error message: mesh is empty')
+end
+if md.mesh.numberofvertices==md.mesh.numberofelements
+	error(['plot error message: the number of elements is the same as the number of nodes...']);
+end
+
+if (isempty(data) | ~isstruct(data)),
+	%first load x,y, etc ... to speed up plot
+
+	if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+		x=md.mesh.x;
+		if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
+		y=md.mesh.y;
+		if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+	else
+		x=md.mesh.long;
+		y=md.mesh.lat;
+	end
+
+	z_field=getfieldvalue(options,'z',md.mesh.z);
+	if ischar(z_field),
+		z=md.(z_field);
+	elseif isnumeric(z_field),
+		z=z_field;
+	else
+		z=md.mesh.z;
+	end
+
+
+	if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
+	elements=md.mesh.elements;
+
+	%is it a 2d plot?
+	if (md.mesh.dimension==2);
+		is2d=1;
+	elseif (md.mesh.dimension==3),
+		if getfieldvalue(options,'layer',0)>=1,
+			is2d=1;
+		else
+			is2d=0;
+		end
+	else
+		error(['dim = ' num2str(md.mesh.dimension) ' not supported yet']);
+	end
+
+	%layer projection? 
+	if getfieldvalue(options,'layer',0)>=1,
+		if strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+			error('processmesh error message: cannot work with 3D meshes for now');
+		end
+		%we modify the mesh temporarily to a 2d mesh from which the 3d mesh was extruded. 
+		x=x2d;
+		y=y2d;
+		z=zeros(size(x2d));
+		elements=elements2d;
+	end
+else
+	%Process Patch
+	if (md.mesh.dimension==2),
+		elements=transpose(reshape(1:3*md.mesh.numberofelements,3,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,3*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,3*md.mesh.numberofelements));
+		z=zeros(3*md.mesh.numberofelements,1);
+		is2d=1;
+	else
+		elements=transpose(reshape(1:6*md.mesh.numberofelements,6,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,6*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,6*md.mesh.numberofelements));
+		z=transpose(reshape(md.mesh.z(data.index)',1,6*md.mesh.numberofelements));
+		is2d=0;
+	end
+end
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if isa(md,'planet'),
+	isplanet=1;
+else
+	isplanet=0;
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/quiver_colorbar.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/quiver_colorbar.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/quiver_colorbar.m	(revision 13101)
@@ -0,0 +1,41 @@
+function quiver_colorbar(quivers,options)
+%QUIVER_COLORBAR - colorbar for quiver plots
+%
+%   Usage:
+%      quiver_colorbar(quivers,options)
+
+if  strcmpi(getfieldvalue(options,'colorbar','on'),'on'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(quivers.levels));
+	for i=1:length(quivers.levels),
+		ticklabel{i}=num2str(round_ice(quivers.levels(i),3));
+	end
+	tickpos=1:quivers.numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(quivers.levels)/4);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+	
+	if exist(options,'colorbartitle'),
+		backup=gca;
+		axes(hcb);lab=title(getfieldvalue(options,'colorbartitle'));
+		set(lab,'Rotation',getfieldvalue(options,'colorbartitlerotation',0));
+		set(lab,'VerticalAlignment','bottom');
+		axes(backup);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/quiver_process.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/quiver_process.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/quiver_process.m	(revision 13101)
@@ -0,0 +1,70 @@
+function [quivers,palette]=quiver_process(x,y,u,v,options)
+%QUIVER_PROCESS - process data for color quiver plot
+%
+%   Usage:
+%      [quivers,palette]=quiver_process(x,y,u,v,options)
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(u) & ~isnan(v));
+x=x(pos); y=y(pos);
+u=u(pos); v=v(pos);
+
+%get Norm Min and Max
+Norm=sqrt(u.^2+v.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%Scale data
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',30);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%create colorind for colors
+colorind=ones(length(u),1);
+for i=1:numcolors
+	pos=find((Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(Norm>levels(end)))=numcolors;
+
+%build output
+quivers=struct('x',x,'y',y,'u',u,'v',v,'levels',levels,'colorind',colorind,'numcolors',numcolors);
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	palette=colormap([0 0 1;1 0 0]);
+elseif numcolors==3,
+	%blue yellow and red
+	palette=colormap([0 0 1;1 1 0;1 0 0]);
+else
+	%let jet choose
+	palette=colormap(jet(numcolors));
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/radarpower.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/radarpower.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/radarpower.m	(revision 13101)
@@ -0,0 +1,118 @@
+function md=radarpower(md,varargin)
+%RADARPOWER - overlay a power radar image on an existing mesh
+%
+%   This routine will overlay a power radar image on an existing mesh.
+%   The power amplitude will be output to vel for now.
+%   In the future, think about a field to hold this value.
+%
+%   Usage:
+%      md=radarpower(md,options);
+%      md=radarpower(md)
+
+%If gdal does not work, uncomment the following line
+%setenv('LD_LIBRARY_PATH','/proj/ice/larour/issm/trunk/externalpackages/gdal/install/lib/');
+%Parse inputs
+if nargin==1,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+
+highres=getfieldvalue(options,'highres',0);
+xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+ylim=getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+posting=getfieldvalue(options,'posting',0); % 0 -> image posting default
+
+%find gdal coordinates
+x0=min(xlim); x1=max(xlim);
+y0=min(ylim); y1=max(ylim);
+
+%figure out if we should go look for Greenland or Antarctica geotiff, or if user provided one.
+if ~exist(options,'overlay_image'),
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if ~exist([jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg']),
+			error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg not found.']);
+		end
+		name = 'mog150_greenland_map';
+		%name = 'mog100_hp1_v10';
+		%name = 'mog500_hp1_v10';
+		jpgim=[jplsvn() '/projects/ModelData/MOG/' name '.jpg'];
+		geom=load([jplsvn() '/projects/ModelData/MOG/' name '.jpgw'],'ascii');
+
+		%geom:   xposting nbcols nbrows yposting xmin ymax
+		xmin=max(geom(5),x0);
+		xmax=min(geom(5)+geom(1)*geom(2),x1);
+		ymin=max(geom(6)-geom(3)*geom(4),y0);
+		ymax=min(geom(6),y1);
+
+		firstcol=max(1,floor((xmin-geom(5))/geom(1))); %x min
+		firstrow=max(1,floor((geom(6)-ymax)/geom(4))); %y max
+		numcols=floor((xmax-xmin)/geom(1)); % x posting
+		numrows=floor((ymax-ymin)/geom(4)); % y posting
+		pixelskip=max(1,ceil(posting/geom(1)));
+
+		%Read and crop file
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+		im=imread(jpgim);
+		im=im(firstrow:firstrow+numrows-1,firstcol:firstcol+numcols-1);
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(xmin:(xmax-xmin)/(size(md.radaroverlay.pwr,2)-1):xmax);
+		md.radaroverlay.y=(ymin:(ymax-ymin)/(size(md.radaroverlay.pwr,1)-1):ymax);
+
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if highres,
+			if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
+		else
+			if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+else
+	%ok, user provided an image. check we also have overlay_xlim and overlay_ylim  options, to know what range of coordinates the image covers.
+	if (~exist(options,'overlay_xlim') | ~exist(options,'overlay_xlim')| ~exist(options,'overlay_xposting')| ~exist(options,'overlay_yposting')),
+		error('radarpower error message: please provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options together with overlay_image option');
+	end
+	overlay_image=getfieldvalue(options,'overlay_image');
+	overlay_xlim=getfieldvalue(options,'overlay_xlim');
+	overlay_ylim=getfieldvalue(options,'overlay_ylim');
+	overlay_xposting=getfieldvalue(options,'overlay_xposting');
+	overlay_yposting=getfieldvalue(options,'overlay_yposting');
+
+	sizex=floor((x1-x0)/overlay_xposting);
+	sizey=floor((y1-y0)/overlay_yposting);
+	topleftx=floor((x0-overlay_xlim(1))/overlay_xposting); % x min
+	toplefty=floor((overlay_ylim(2)-y1)/overlay_yposting); % y max
+
+	%Read and crop file
+	disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	im=imread(overlay_image);
+	im=im(toplefty:toplefty+sizey,topleftx:topleftx+sizex);
+	md.radaroverlay.pwr=double(flipud(im));
+	md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+	md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/scaleruler.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/scaleruler.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/scaleruler.m	(revision 13101)
@@ -0,0 +1,61 @@
+function scaleruler(options)
+%SCALERULER - overlay a scale ruler on current plot
+%
+%   Usage:
+%      scaleruler(options)
+
+%get options
+structure=getfieldvalue(options,'scaleruler');
+fontsize=getfieldvalue(options,'scaleruler_fontsize',16);
+
+%Go through structure and fill missing arguments
+if length(structure)~=5
+	error('plotmodel error message: bad number of input arguments for scaleruler: [x0 y0 length thickness numberofticks]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengthscale=structure(3);
+widthscale=structure(4);
+numberofticks=structure(5);
+
+%initialize some coordinates
+unitlength=lengthscale/(numberofticks -1);
+flag=-1;
+
+Bd=[x0 y0];
+Bu=[x0 y0+widthscale];
+Tick=0;
+
+%Text
+xt=Bu(1);
+yt=Bu(2)+widthscale;
+text(xt,yt,num2str(Tick),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+
+%loope over the patches
+for i=1:numberofticks-1,
+	Au=Bu;
+	Ad=Bd;
+	Bu=[Au(1)+unitlength Ad(2)+widthscale];
+	Bd=[Ad(1)+unitlength Ad(2)];
+	Tick=Tick+unitlength;
+
+	%pathes
+	if flag==-1
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'Black','FaceAlpha',0.5);
+	else
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'White','FaceAlpha',0.3);
+	end
+
+	%flip flag
+	flag=-flag;
+
+	%Text
+	xt=Bu(1);
+	yt=Bu(2)+widthscale;
+	if i~=numberofticks-1,
+		text(xt,yt,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+	end
+end
+text(xt,yt,[num2str(round_ice(Tick/1000,3)) ' km'],'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
Index: /issm/branches/trunk-jpl-damage/src/m/plot/showregion.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/showregion.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/showregion.m	(revision 13101)
@@ -0,0 +1,34 @@
+function showregion(md,insetpos)
+%SHOWREGION - show region on plot
+%
+%   Usage:
+%      showregion(md,insetpos);
+
+%get inset relative position (x,y,width,height)
+%insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+
+%get current plos position
+cplotpos=get(gca,'pos');
+%compute inset position
+PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+axes('pos',PosInset);
+axis equal off
+%box off
+if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+	A=expread([issmdir() 'projects/Exp/Greenland.exp']);
+elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+	A=expread([issmdir() '/projects/Exp/Antarctica.exp']);
+else
+	error('applyoptions error message: hemisphere not defined');
+end
+
+Ax=[min(A.x) max(A.x)];
+Ay=[min(A.y) max(A.y)];
+
+mdx=[min(md.mesh.x) max(md.mesh.x)];
+mdy=[min(md.mesh.y) max(md.mesh.y)];
+
+line(A.x,A.y,'color','b');
+patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
+patch( [mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+colorbar('off');
Index: /issm/branches/trunk-jpl-damage/src/m/plot/squarezoom.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/squarezoom.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/squarezoom.m	(revision 13101)
@@ -0,0 +1,20 @@
+function squarezoom()
+%SQUAREZOOM - zoom on a part of a figure
+%
+%   Usage:
+%      squarezoom()
+
+disp('Click twice to define a square where you want to zoom. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+dx=x(2)-x(1);
+dy=y(1)-y(2);
+
+if dx>dy,
+	delta=dx-dy;
+	xlim([x(1) x(2)]);
+	ylim([y(2)-delta/2 y(1)+delta/2]);
+else
+	delta=dy-dx;
+	xlim([x(1)-delta/2 x(2)+delta/2]);
+	ylim([y(2) y(1)]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/plot/subplotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/plot/subplotmodel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/plot/subplotmodel.m	(revision 13101)
@@ -0,0 +1,35 @@
+function ha=subplotmodel(nlines,ncols,num,options);
+%SUBPLOTMODEL -  tight subplot that includes margins
+%
+%   Usage:
+%      h=subplotmodel(nlines,ncols,i,options)
+
+%Regular subplot
+if ~exist(options,'tightsubplot')
+	subplot(nlines,ncols,num);
+	return;
+end
+
+gap     = getfieldvalue(options,'gap',[.01 .01]);
+hmargin = getfieldvalue(options,'hmargin',[.01 .01]);
+vmargin = getfieldvalue(options,'vmargin',[.01 .01]);
+
+height = (1-sum(vmargin)-(nlines-1)*gap(1))/nlines; 
+width  = (1-sum(hmargin)-(ncols-1)*gap(2))/ncols;
+ymin   = 1-vmargin(2)-height; 
+
+for i = 1:nlines
+	xmin = hmargin(1);
+	for j = 1:ncols
+		if(((i-1)*ncols+j)==num)
+			ha = axes('Units','normalized', ...
+				'Position',[xmin ymin width height],'XTickLabel','','YTickLabel','','Visible','off');
+			return
+		end
+		xmin = xmin+width+gap(2);
+	end
+	ymin = ymin-height-gap(1);
+end
+
+%Activate new axes
+axes(ha);
Index: /issm/branches/trunk-jpl-damage/src/m/print/printmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/print/printmodel.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/print/printmodel.m	(revision 13101)
@@ -0,0 +1,100 @@
+function printmodel(filename,format,varargin)
+%PRINTMODEL - save an image of current figure
+%
+%   filename: output name of image file (no extension)
+%   format: image format (ex: 'tiff','jpg','pdf') 
+%
+%   List of options to printfmodel: 
+%
+%   figure: number of figure to print (default: current figure)
+%   resolution: use higher resolution to anti-alias (default 2)
+%   margin: add margin around final image  
+%   marginsize: size of margin around final image (default 5)
+%   frame: add frame around final image
+%   framesize: size of frame around final image (default 5)
+%   framecolor: color of frame around final image (default 'black')
+%   trim: trim empty space around image (default 'off')
+%   hardcopy: 'off' to impose MATLAB to use the same colors (default 'off')
+%   
+%   Usage:
+%      printmodel(filename,format,varargin);
+%
+%   Examples:
+%      printmodel('image','tiff')
+%      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
+
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'figure','gcf');
+options=addfielddefault(options,'format','tiff');
+options=addfielddefault(options,'resolution',1);
+options=addfielddefault(options,'margin','on');
+options=addfielddefault(options,'marginsize',25);
+options=addfielddefault(options,'frame','on');
+options=addfielddefault(options,'framesize',3);
+options=addfielddefault(options,'framecolor','black');
+options=addfielddefault(options,'trim','on');
+options=addfielddefault(options,'hardcopy','off');
+
+%get fig: 
+fig=getfieldvalue(options,'figure');
+if ischar(fig),
+	fig=gcf;
+else
+	figure(fig);
+	fig=gcf;
+end
+
+%In auto mode, MATLAB prints the figure the same size as it appears on the computer screen, centered on the page
+set(fig, 'PaperPositionMode', 'auto');
+
+%InvertHardcopy off imposes MATLAB to use the same colors
+set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
+
+
+%we could have several formats, as a cell array of strings.
+formats=format;
+if ~iscell(formats),
+	formats={formats};
+end
+
+%loop on formats:
+for i=1:length(formats),
+	format=formats{i};
+
+	%Use higher resolution to anti-alias and use zbuffer to have smooth colors
+	print(fig, '-zbuffer','-dtiff',['-r' num2str(get(0,'ScreenPixelsPerInch')*getfieldvalue(options,'resolution'))],filename);
+
+	%some trimming involved? 
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'trim'),'on'),
+			system(['convert -trim ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%margin?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'margin'),'on'),
+			marginsize=getfieldvalue(options,'marginsize');
+			system(['convert -border ' num2str(marginsize) 'x' num2str(marginsize) ' -bordercolor "white" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%frame?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'frame'),'on'),
+			framesize=getfieldvalue(options,'framesize');
+			framecolor=getfieldvalue(options,'framecolor');
+			system(['convert -border ' num2str(framesize) 'x' num2str(framesize) ' -bordercolor "' framecolor '" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%convert image to correct format
+	if ~strcmpi(format,'tiff') & ~strcmpi(format,'tif'),
+		system(['convert ' filename '.tif ' filename '.' format]);
+		delete([ filename '.tif']);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/lclist_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/lclist_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/lclist_write.m	(revision 13101)
@@ -0,0 +1,62 @@
+%
+%  function to write linear constraint list
+%
+function []=lclist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put linear constraints into lists for writing
+
+nvar=0;
+pmatrix=[];
+plower =[];
+pupper =[];
+ptarget=[];
+pstype =[];
+pscale =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pmatrix=[pmatrix prop_matrix(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+end
+
+%  write linear constraints
+
+disp(sprintf('  Writing %d %s linear constraints.',...
+    nvar,cstring));
+
+if ~isempty(pmatrix)
+    fprintf(fidi,'\t  %s_matrix =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmatrix,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/param_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/param_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/param_write.m	(revision 13101)
@@ -0,0 +1,24 @@
+%
+%  function to write a parameter
+%
+function []=param_write(fidi,sbeg,pname,smid,send,params)
+
+if ~isfield(params,pname)
+    warning('param_write:param_not_found',...
+        'Parameter ''%s'' not found in structure.',pname);
+    return
+end
+
+if islogical(params.(pname)) && ~params.(pname)
+    return
+end
+
+if     islogical(params.(pname))
+    fprintf(fidi,[sbeg '%s' send],pname);
+elseif ischar   (params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%s' send],pname,params.(pname));
+elseif isnumeric(params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%g' send],pname,params.(pname));
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/rlev_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/rlev_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/rlev_write.m	(revision 13101)
@@ -0,0 +1,66 @@
+%
+%  function to write response levels
+%
+function []=rlev_write(fidi,dresp,params)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+
+nresp=0;
+respl={};
+probl={};
+rell ={};
+grell={};
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    [respli,probli,relli,grelli]=prop_levels(dresp.(fnames{i}));
+    respl=[respl respli];
+    probl=[probl probli];
+    rell =[rell  relli ];
+    grell=[grell grelli];
+end
+
+%  write response levels
+
+param_write(fidi,'\t  ','distribution',' ','\n',params);
+if ~isempty(respl)
+    rlevi_write(fidi,'response_levels',respl);
+    param_write(fidi,'\t  ','compute',' ','\n',params);
+end 
+if ~isempty(probl)
+    rlevi_write(fidi,'probability_levels',probl);
+end
+if ~isempty(rell)
+    rlevi_write(fidi,'reliability_levels',rell);
+end
+if ~isempty(grell)
+    rlevi_write(fidi,'gen_reliability_levels',grell);
+end
+
+end
+
+%
+%  function to each type of response level
+%
+function []=rlevi_write(fidi,ltype,levels)
+
+fprintf(fidi,'\t  num_%s =',ltype);
+for i=1:numel(levels)
+    fprintf(fidi,' %d',length(levels{i}));
+end
+fprintf(fidi,'\n');
+
+fprintf(fidi,'\t  %s =\n',ltype);
+
+for i=1:numel(levels)
+    if ~isempty(levels{i})
+        vector_write(fidi,sprintf('\t    '),levels{i},8,76);
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/rlist_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/rlist_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/rlist_write.m	(revision 13101)
@@ -0,0 +1,70 @@
+%
+%  function to write response list
+%
+function [rdesc]=rlist_write(fidi,cstring,cstring2,dresp,rdesc)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+%  (and accumulate descriptors into list for subsequent writing)
+
+nresp=0;
+pstype =[];
+pscale =[];
+pweight=[];
+plower =[];
+pupper =[];
+ptarget=[];
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    pstype =[pstype  prop_stype(dresp.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dresp.(fnames{i})) ];
+    pweight=[pweight prop_weight(dresp.(fnames{i}))];
+    plower =[plower  prop_lower(dresp.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dresp.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dresp.(fnames{i}))];
+    rdesc  =[rdesc   prop_desc(dresp.(fnames{i}),fnames{i})];
+end
+
+%  write responses
+
+disp(sprintf('  Writing %d %s responses.',nresp,cstring));
+
+fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pweight)
+    switch cstring2
+        case 'objective_function'
+            fprintf(fidi,'\t  %s_weights =\n','multi_objective');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+        case 'least_squares_term'
+            fprintf(fidi,'\t  %s_weights =\n','least_squares');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+    end
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+
+end
+
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/vector_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/vector_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/vector_write.m	(revision 13101)
@@ -0,0 +1,52 @@
+
+%%  function to write a vector on multiple lines
+
+function []=vector_write(fidi,sbeg,vec,nmax,cmax)
+
+if ~exist('nmax','var') || isempty(nmax)
+    nmax=Inf;
+end
+if ~exist('cmax','var') || isempty(cmax)
+    cmax=Inf;
+end
+
+%  set up first iteration
+
+svec =[];
+nitem=nmax;
+lsvec=cmax;
+
+%  transpose vector from column-wise to row-wise
+
+vec=vec';
+
+%  assemble each line, flushing when necessary
+
+for i=1:numel(vec)
+    if isnumeric(vec(i))
+        sitem=sprintf('%g'    ,vec(i));
+    else
+        sitem=sprintf('''%s''',char(vec(i)));
+    end
+    nitem=nitem+1;
+    lsvec=lsvec+1+length(sitem);
+    
+    if (nitem <= nmax) && (lsvec <= cmax)
+        svec=[svec ' ' sitem];
+    else
+        if ~isempty(svec)
+            fprintf(fidi,'%s\n',svec);
+        end
+        svec=[sbeg sitem];
+        nitem=1;
+        lsvec=length(svec);
+    end
+end
+
+%  flush buffer at end, if necessary
+
+if ~isempty(svec)
+    fprintf(fidi,'%s\n',svec);
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/vlist_write.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/vlist_write.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/vlist_write.m	(revision 13101)
@@ -0,0 +1,80 @@
+%
+%  function to write variable list
+%
+function []=vlist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put variables into lists for writing
+
+nvar=0;
+pinitpt=[];
+plower =[];
+pupper =[];
+pmean  =[];
+pstddev=[];
+pinitst=[];
+pstype =[];
+pscale =[];
+pdesc  =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pinitpt=[pinitpt prop_initpt(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    pmean  =[pmean   prop_mean(dvar.(fnames{i}))  ];
+    pstddev=[pstddev prop_stddev(dvar.(fnames{i}))];
+    pinitst=[pinitst prop_initst(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+    pdesc  =[pdesc   prop_desc(dvar.(fnames{i}),fnames{i})];
+end
+
+%  write variables
+%  (using Dakota 4.1 syntax for backward compatability)
+
+disp(sprintf('  Writing %d %s variables.',nvar,cstring));
+
+fprintf(fidi,'\t%s = %d\n',cstring,nvar);
+if ~isempty(pinitpt)
+    fprintf(fidi,'\t  %s_initial_point =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitpt,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(pmean)
+    fprintf(fidi,'\t  %s_means =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmean  ,6,76);
+end
+if ~isempty(pstddev)
+    fprintf(fidi,'\t  %s_std_deviations =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstddev,6,76);
+end
+if ~isempty(pinitst)
+    fprintf(fidi,'\t  %s_initial_state =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitst,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pdesc)
+    fprintf(fidi,'\t  %s_descriptors =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pdesc  ,6,76);
+end
+
+end
Index: /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrain.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrain.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrain.m	(revision 13101)
@@ -0,0 +1,63 @@
+function md=BasinConstrain(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))))~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrainShelf.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrainShelf.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/BasinConstrainShelf.m	(revision 13101)
@@ -0,0 +1,74 @@
+function md=BasinConstrainShelf(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure any node with NaN velocity is spc'd:
+%we spc to the smoothed value, so that control methods don't go berserk trying to figure out what reaction force to apply for the spc to stand.
+pos=find(isnan(md.inversion.vel_obs_raw));
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%iceshelves: any vertex on floating ice is spc'd
+pos=find(md.mask.vertexongroundedice);
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))) )~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/branches/trunk-jpl-damage/src/m/regional/basinzoom.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/basinzoom.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/basinzoom.m	(revision 13101)
@@ -0,0 +1,94 @@
+function varargout=basinzoom(varargin)
+%ANTZOOM - zoom on a basin in Antarctica or Greenland.
+%
+%   This function zooms on an existing figure describing Antarctica or Greenland 
+%   The zooming depends on the region name provided as input. 
+%
+%   Usage:
+%      varargout=basinzoom(options)
+
+%recover some options, and set defaults
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+unitmultiplier=getfieldvalue(options,'unit',NaN);
+basin=getfieldvalue(options,'basin');
+
+if exist(options,'basindelta'),
+
+	basindeltax=getfieldvalue(options,'basindelta',300); 
+	basindeltay=getfieldvalue(options,'basindelta',300); 
+else
+	basindeltax=getfieldvalue(options,'basindeltax',300); 
+	basindeltay=getfieldvalue(options,'basindeltay',300);
+end
+
+%multiply by 1000 to get kms
+basindeltax=basindeltax*1000;
+basindeltay=basindeltay*1000;
+
+%Ok, find basin we are talking about: 
+load([jplsvn() '/projects/ModelData/Names/Names.mat']);
+		
+%Go through names: 
+found=0;
+for i=1:size(names,1),
+	if strcmpi(names{i,1},basin),
+		%ok, we've got the region. Get lat and long: 
+		long=names{i,2};
+		lat=names{i,3};
+		hemisphere=names{i,4};
+		found=1;
+		break;
+	end
+end
+
+if ~found,
+	error(['basinzoom error message: cannot find basin ' basin '. Use isbasin to determine a basin name.']);
+end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Transform lat long into x,y: 
+[xc,yc]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%compute x0,x1 and y0,y1 using basindeltax and basindeltay
+x0=xc-basindeltax/2;
+x1=xc+basindeltax/2;
+y0=yc-basindeltay/2;
+y1=yc+basindeltay/2;
+
+if ~isnan(unitmultiplier)
+	x0=x0*unitmultiplier;
+	x1=x1*unitmultiplier;
+	y0=y0*unitmultiplier;
+	y1=y1*unitmultiplier;
+end
+
+%if output arguments are present, return the limits, 
+%otherwise, set them on the current graphic. 
+if nargout==2,
+	found=1;
+	varargout{1}=[x0 x1];
+	varargout{2}=[y0 y1];
+else
+	xlim([x0 x1]);
+	ylim([y0 y1]);
+	found=1;
+	daspect([1;1;1]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/regional/isbasin.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/isbasin.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/isbasin.m	(revision 13101)
@@ -0,0 +1,17 @@
+function isbasin(name)
+%ISBASIN: figure out if a basin name exists.
+%
+%
+%        Usage:  index=isbasin('jks');
+%
+%
+
+%First, load basin names:
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
+
+%go through names: 
+for i=1:length(names),
+	if ~isempty(strfind(names{i,1},name)),
+		disp(['''' names{i,1} ''' Long:' num2str(names{i,2}) ' Lat:' num2str(names{i,3}) ]);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/regional/plotbasins.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/plotbasins.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/plotbasins.m	(revision 13101)
@@ -0,0 +1,18 @@
+%display all the domain outlines in a directory
+
+basins=listfiles;
+
+hold on
+for i=1:length(basins), 
+	%check whether this is a .exp file
+	basin=basins{i};
+	if strcmpi(basin(end-3:end),'.exp'),
+
+		contour=expread(basin,0);
+		x=contour(1).x;
+		y=contour(1).y;
+		x0=mean(x); y0=mean(y);
+		text(x0,y0,basin(1:end-4),'Fontsize',14);
+		expdisp(basin);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/regionaltransient2d.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/regionaltransient2d.m	(revision 13101)
@@ -0,0 +1,158 @@
+function md2=regionaltransient2d(md1,area,hmin,hmax,err,stepres)
+%regionaltransient2d - extract a model according to an Argus contour or flag list and remesh
+%               at new resolution res
+%
+%   This routine extracts a submodel from a bigger model with respect to a given contour
+%   md must be followed by the corresponding exp domain file (argus type, .exp extension). 
+%   The model will be remeshed at high rsolution hmin and low resolution hmax.  The ice 
+%   boundary velocities will be spc'd to the transient velocities at saved transient steps
+%   at the resolution optionally provided for stepres.  A stepres of 2 means that you wish
+%   to skip every other saved transient step.  This is useful when extracting a long transient.
+%
+%   Usage:
+%      md2=regionaltransient2d(md1,area,hmin,hmax,err);
+%
+%   Examples:
+%      md2=regionaltransient2d(md,'Domain.exp',500,10000,[15 250]);
+%      md2=regionaltransient2d(md,'Domain.exp',3000,15000,[10 300],2);
+%
+%   See also: MODELEXTRACT, EXTRUDE, COLLAPSE
+
+%some checks
+if ((nargin~=5) & (nargin~=6)),
+	help regionaltransient2d 
+	error('regionaltransient2d error message: bad usage');
+end
+
+%get check option
+if (nargin==5),
+	stepres=1;
+end
+
+%take every fields from model
+mde=modelextract(md1,area);
+mde.private.bamg=[];
+mde.mesh.extractedvertices=nan;
+mde.mesh.extractedelements=nan;
+
+%remesh
+md2=bamg(mde,'hmin',hmin,'hmax',hmax,'field',[mde.inversion.vel_obs mde.geometry.surface],'splitcorner',1,'KeepVertices',0,'err',err);
+md2=setmask(md2,'','');
+
+%automatically modify fields
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+
+		%get field
+		field=md1.(model_fields{i});
+		fieldsize=size(field);
+
+		%copy field, interpolated to new mesh
+		if isobject(field), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			fname=['(model_fields{i}).(object_fields{j})'];
+		else
+			object_fields=field;
+			fname=['(model_fields{i})'];
+		end
+		for j=1:length(object_fields),
+			%get field
+			field=eval(['md2.' fname]);
+			fieldsize=size(field);
+
+			%size = number of nodes * n
+			for n=1:fieldsize(2)
+				if fieldsize(1)==mde.mesh.numberofvertices
+					if(sum(field(:,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=field(1,n)*ones(md2.mesh.numberofvertices,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices,n);']);
+				elseif fieldsize(1)==mde.mesh.numberofvertices+1
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[field(1,n)*ones(md2.mesh.numberofvertices,1); field(end,n)];']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(1:end-1,n),md2.mesh.x,md2.mesh.y); field(end,n)];']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices+1,n)']);
+					%size = number of elements * n
+				elseif fieldsize(1)==mde.mesh.numberofelements
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=field(1,n)*ones(md2.mesh.numberofelements,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofelements,n);']);
+				end
+			end
+		end
+	end
+
+	%Read transient velocities and thickness, looping through only the populated times
+	spcx=[];
+	spcy=[];
+	spct=[];
+	steps=[];
+	nsteps=length(md1.results.TransientSolution);
+	count=0;
+	numElements=arrayfun(@(x) numel(x.step), md1.results.TransientSolution);
+	for t=find(numElements==1)
+		if ~isempty(md1.results.TransientSolution(t).Vel) & mod(count,stepres)==0,
+			vx=PatchToVec(md1.results.TransientSolution(t).Vx);
+			vy=PatchToVec(md1.results.TransientSolution(t).Vy);
+			thickness=PatchToVec(md1.results.TransientSolution(t).Thickness);
+			spcx=[spcx InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
+			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vy,md2.mesh.x,md2.mesh.y)];
+			spct=[spct InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,thickness,md2.mesh.x,md2.mesh.y)];
+			steps=[steps t*md1.timestepping.time_step];
+		end
+		count=count+1;
+	end
+
+	%As long as there are recorded time steps, spc the boundaries with velocities
+	if nsteps > 0
+		md2.diagnostic.spcvx=md2.diagnostic.spcvx*ones(1,size(spcx,2));
+		md2.diagnostic.spcvy=md2.diagnostic.spcvy*ones(1,size(spcy,2));
+		md2.diagnostic.spcvz=md2.diagnostic.spcvz*ones(1,size(spcx,2));
+		md2.prognostic.spcthickness=md2.prognostic.spcthickness*ones(1,size(spct,2));
+		md2.diagnostic.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvz(find(md2.mesh.vertexonboundary),:)=0;
+		md2.prognostic.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvx=[md2.diagnostic.spcvx; steps];
+		md2.diagnostic.spcvy=[md2.diagnostic.spcvy; steps];
+		md2.diagnostic.spcvz=[md2.diagnostic.spcvz; steps];
+		md2.prognostic.spcthickness=[md2.prognostic.spcthickness; steps];
+	end
+
+	%Diagnostic.  Don't spc the icefront vertices.
+	if ~isnan(md2.diagnostic.icefront)
+		md1s=modelextract(md1,area);
+		%md2.diagnostic.icefront=[md2.mesh.segments 2];
+		e2=md2.mesh.segments(:,end);
+		e1=md1s.mesh.segments(:,end);
+
+		pload = nan*ones(size(md1s.mesh.elements,1),1);
+		pload(md1s.diagnostic.icefront(:,end-1))=md1s.diagnostic.icefront(:,end);
+
+		x2=mean(md2.mesh.x(md2.mesh.elements(e2,:)),2);
+      y2=mean(md2.mesh.y(md2.mesh.elements(e2,:)),2);
+		x1=mean(md1s.mesh.x(md1s.mesh.elements),2);
+      y1=mean(md1s.mesh.y(md1s.mesh.elements),2);
+
+		pload2=griddata(x1,y1,pload,x2,y2,'nearest');
+		md2.diagnostic.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
+		md2.diagnostic.spcvx(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvy(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvz(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.prognostic.spcthickness(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+	end
+
+	%Clear results fields
+	if isstruct(md1.results),
+		md2.results=[];
+	end
+
Index: /issm/branches/trunk-jpl-damage/src/m/regional/showbasins.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/regional/showbasins.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/regional/showbasins.m	(revision 13101)
@@ -0,0 +1,69 @@
+function showbasins(varargin)
+%SHOWBASINS - return basins that are within the xlim and ylim
+%
+%   Usage:
+%      names=showbasins(options);
+%   Options: 
+%      'unit' default 1
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+
+%recover some options, and set defaults
+unitmultiplier=getfieldvalue(options,'unit',1);
+fontsize=getfieldvalue(options,'fontsize',12);
+hemisphere=getfieldvalue(options,'hemisphere');
+
+if strcmpi(hemisphere,'s'),
+	hemisphere=-1;
+elseif strcmpi(hemisphere,'n'),
+	hemisphere=+1;
+else
+	error('showbasins error message: hemispehre should be either ''n'' or ''s''');
+	end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Ok, find basin we are talking about: 
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
+
+%Get xlim and ylim, and convert into lat,long: 
+xlimits=xlim; x0=xlimits(1); x1=xlimits(2);
+ylimits=ylim; y0=ylimits(1); y1=ylimits(2);
+
+%Convert names lat and long into x,y:
+lat=cell2mat(names(:,3));
+long=cell2mat(names(:,2));
+
+%Now, convert lat,long into x,y:
+[x,y]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%Find  x,y within xlimits and ylimits: 
+locations=find(x>x0 & x<x1 & y>y0 & y<y1);
+
+%Go through locations, and display the names: 
+for i=1:size(locations,1),
+	hold on,
+	plot(x(locations(i)),y(locations(i)),'r.');
+	t=text(x(locations(i)),y(locations(i)),names{locations(i),1}); 
+	set(t,'FontSize',fontsize);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.m	(revision 13101)
@@ -0,0 +1,65 @@
+function structure=MatlabProcessPatch(structure);
+%PROCESSPATCH - create a structure from a patch
+%
+%   Usage:
+%      Result=ProcessPatch(Result);
+
+%return if there is no field Patch
+if (~isfield(structure,'Patch')),
+	return;
+end
+
+%loop over steps
+for i=1:length(structure),
+
+	%Get Patch for current step
+	Patch=structure(i).Patch;
+	numvertices=structure(i).PatchVertices;
+
+	%check that Patch is not empty
+	if length(Patch)==0 continue; end
+
+	%Get number of fields;
+	fields=unique(Patch(:,1));
+	steps=unique(Patch(:,2));
+
+	%parse steps
+	for j=1:length(steps),
+
+		posstep=find(Patch(:,2)==steps(j));
+
+		%Take all the lines of the Patch for this timestep
+		temporarypatch=Patch(posstep,:);
+		time=temporarypatch(1,3);
+		step=temporarypatch(1,2);
+
+		%parse fields
+		for i=1:length(fields),
+
+			%get name
+			fieldname=EnumToString(fields(i));
+
+			%get line positions
+			pos=find(temporarypatch(:,1)==fields(i));
+
+			%Fill Result structure
+			structure(step).steps=step;
+			structure(step).time=time;
+			structure(step).(fieldname).element=temporarypatch(pos,4);
+			structure(step).(fieldname).interpolation=temporarypatch(pos,5);
+			structure(step).(fieldname).index=temporarypatch(pos,6:5+numvertices);
+			if structure(step).(fieldname).interpolation==P1Enum(),
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices:end);
+			end
+			if structure(step).(fieldname).interpolation==P0Enum(),
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices);
+			end
+
+		end
+	end
+end
+
+%remove fields
+structure=rmfield(structure,'Patch');
+structure=rmfield(structure,'PatchVertices');
+structure=rmfield(structure,'PatchNodes');
Index: /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/MatlabProcessPatch.py	(revision 13101)
@@ -0,0 +1,19 @@
+def MatlabProcessPatch(structure):
+	"""
+	PROCESSPATCH - create a structure from a patch
+ 
+	   Usage:
+	      Result=ProcessPatch(Result);
+	"""
+
+	#loop over steps
+	for structurei in structure.itervalues():
+
+		#return if there is no field Patch
+		if 'Patch' not in structurei:
+			continue
+
+		raise SystemError("MatlabProcessPatch not implemented in Python.")
+
+	return structure
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.m	(revision 13101)
@@ -0,0 +1,260 @@
+function WriteData(fid,varargin)
+%WRITEDATA - write model field in binary file
+%
+%   Usage:
+%      WriteData(fid,varargin);
+
+%process options
+options=pairoptions(varargin{:});
+
+%Get data properties
+if exist(options,'object');
+	%This is a object field, construct enum and data
+	obj       = getfieldvalue(options,'object');
+	fieldname = getfieldvalue(options,'fieldname');
+	classname = class(obj);
+
+	enum      = BuildEnum([classname '_' fieldname]);
+	data      = obj.(fieldname);
+else
+	%No processing required
+	data = getfieldvalue(options,'data');
+	enum = getfieldvalue(options,'enum');
+end
+format  = getfieldvalue(options,'format');
+mattype = getfieldvalue(options,'mattype',0);    %only required for matrices
+
+%Process sparse matrices
+if issparse(data),
+	data=full(data);
+end
+
+%Step 1: write the enum to identify this record uniquely
+fwrite(fid,enum,'int'); 
+
+%Step 2: write the data itself.
+if     strcmpi(format,'Boolean'),% {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 bool (disguised as an int)+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int');  %send an int, not easy to send a bool
+	% }}}
+elseif strcmpi(format,'Integer'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 integer + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int'); 
+	% }}}
+elseif strcmpi(format,'Double'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,8+4,'int');  %1 double+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write double
+	fwrite(fid,data,'double'); 
+	% }}}
+elseif strcmpi(format,'String'), % {{{
+	%first write length of record
+	fwrite(fid,length(data)+4+4,'int');  %string + string size + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write string
+	fwrite(fid,length(data),'int'); 
+	fwrite(fid,data,'char'); 
+	% }}}
+elseif strcmpi(format,'BooleanMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'IntMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'DoubleMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'MatArray'), % {{{
+
+	numrecords=numel(data);
+
+	%first get length of record
+	recordlength=4+4; %number of records + code
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		recordlength=recordlength+4*2+... %row and col of matrix
+			s(1)*s(2)*8; %matrix of doubles
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%write data, first number of records
+	fwrite(fid,numrecords,'int'); 
+
+	%write each matrix: 
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		fwrite(fid,s(1),'int'); 
+		fwrite(fid,s(2),'int'); 
+		fwrite(fid,matrix','double');
+	end
+	% }}}
+elseif strcmpi(format,'StringArray'), % {{{
+
+	%first get length of string array: 
+	num=numel(data);
+	%now get length of record: 
+	recordlength=4+4; %for length of array + code
+	for i=1:num,
+		string=data{i};
+		recordlength=recordlength+4+length(string); %for each string
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write length of string array
+	fwrite(fid,num,'int'); 
+
+	%now write the strings
+	for i=1:num,
+		string=data{i};
+		fwrite(fid,length(string),'int'); 
+		fwrite(fid,string,'char'); 
+	end
+	% }}}
+else  % {{{
+	error(['WriteData error message: data type: ' num2str(format) ' not supported yet! (' EnumToString(enum) ')']);
+end % }}}
+end
+
+function enum=BuildEnum(string) % {{{
+%BUILDENUM - build enum out of string
+%
+%   Usage:
+%      enum=BuildEnum(string)
+
+	if findstr(string,'_'),
+		indices=findstr(string,'_');
+		for i=1:length(indices),
+			string(indices(i)+1)=upper(string(indices(i)+1));
+		end
+		string(indices)=[];
+	end
+
+	%take first letter of string and make it uppercase: 
+	string(1)=upper(string(1));
+
+	%Get Enum
+	enum=eval([string 'Enum();']); 
+end % }}}
+function code=FormatToCode(format) % {{{
+%This routine takes the format string, and hardcodes it into an integer, which 
+%is passed along the record, in order to identify the nature of the dataset being 
+%sent.
+	if     strcmpi(format,'Boolean'),
+		code=1;
+	elseif strcmpi(format,'Integer'), 
+		code=2;
+	elseif strcmpi(format,'Double'), 
+		code=3;
+	elseif strcmpi(format,'String'), 
+		code=4;
+	elseif strcmpi(format,'BooleanMat'),
+		code=5;
+	elseif strcmpi(format,'IntMat'),
+		code=6;
+	elseif strcmpi(format,'DoubleMat'),
+		code=7;
+	elseif strcmpi(format,'MatArray'), 
+		code=8;
+	elseif strcmpi(format,'StringArray'),
+		code=9;
+	else 
+		error('FormatToCode error message: data type not supported yet!');
+	end
+end% }}}
Index: /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/WriteData.py	(revision 13101)
@@ -0,0 +1,313 @@
+import numpy
+import math
+import struct
+from pairoptions import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def WriteData(fid,*args):
+	"""
+	WRITEDATA - write model field in binary file
+ 
+	   Usage:
+	      WriteData(fid,varargin)
+	"""
+
+	#process options
+	#  the import above the function level doesn't work?
+	from pairoptions import *
+	options=pairoptions(*args)
+
+	#Get data properties
+	if options.exist('object'):
+		#This is an object field, construct enum and data
+		obj       = options.getfieldvalue('object')
+		fieldname = options.getfieldvalue('fieldname')
+		classname = str(type(obj)).rsplit('.')[-1].split("'")[0]
+
+		enum      = BuildEnum(classname+'_'+fieldname)
+		data      = getattr(obj,fieldname)
+	else:
+		#No processing required
+		data = options.getfieldvalue('data')
+		enum = options.getfieldvalue('enum')
+	format  = options.getfieldvalue('format')
+	mattype = options.getfieldvalue('mattype',0)    #only required for matrices
+
+	#Process sparse matrices
+#	if issparse(data),
+#		data=full(data);
+#	end
+
+	#Step 1: write the enum to identify this record uniquely
+	fid.write(struct.pack('i',enum)) 
+
+	#Step 2: write the data itself.
+	if   strcmpi(format,'Boolean'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 bool (disguised as an int)+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',int(data)))  #send an int, not easy to send a bool
+		# }}}
+
+	elif strcmpi(format,'Integer'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 integer + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',data)) 
+		# }}}
+
+	elif strcmpi(format,'Double'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',8+4))  #1 double+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write double
+		fid.write(struct.pack('d',data)) 
+		# }}}
+
+	elif strcmpi(format,'String'):    # {{{
+		#first write length of record
+		fid.write(struct.pack('i',len(data)+4+4))  #string + string size + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write string
+		fid.write(struct.pack('i',len(data))) 
+		fid.write(struct.pack('%ds' % len(data),data)) 
+		# }}}
+
+	elif strcmpi(format,'BooleanMat'):    # {{{
+
+		if isinstance(data,bool):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'IntMat'):    # {{{
+
+		if isinstance(data,(int,long)):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'DoubleMat'):    # {{{
+
+		if isinstance(data,(bool,int,long,float)):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'MatArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #number of records + code
+		for matrix in data:
+			if isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			if len(matrix.shape) == 1:
+				if numpy.size(matrix):
+					matrix=matrix.reshape(numpy.size(matrix),1)
+				else:
+					matrix=matrix.reshape(0,0)
+
+			s=matrix.shape
+			recordlength+=4*2+s[0]*s[1]*8    #row and col of matrix + matrix of doubles
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#write data, first number of records
+		fid.write(struct.pack('i',len(data))) 
+
+		#write each matrix: 
+		for matrix in data:
+			if isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			if len(matrix.shape) == 1:
+				matrix=matrix.reshape(numpy.size(matrix),1)
+
+			s=matrix.shape
+			fid.write(struct.pack('i',s[0])) 
+			fid.write(struct.pack('i',s[1])) 
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					fid.write(struct.pack('d',float(matrix[i][j])))
+		# }}}
+
+	elif strcmpi(format,'StringArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #for length of array + code
+		for string in data:
+			recordlength+=4+len(string)    #for each string
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write length of string array
+		fid.write(struct.pack('i',len(data))) 
+
+		#now write the strings
+		for string in data:
+			fid.write(struct.pack('i',len(string))) 
+			fid.write(struct.pack('%ds' % len(string),string)) 
+		# }}}
+
+	else:    # {{{
+		raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,EnumToString(enum)[0]))
+	# }}}
+
+def BuildEnum(string): # {{{
+	"""
+	BUILDENUM - build enum out of string
+ 
+    Usage:
+       enum=BuildEnum(string)
+	"""
+
+	if '_' in string:
+		substrs=string.split('_')
+		string=''
+		for substr in substrs:
+			string+=substr[0].upper()+substr[1:]
+	else:
+		#take first letter of string and make it uppercase: 
+		string=string[0].upper()+string[1:]
+
+	#Get Enum
+	exec('enum='+string+'Enum()',globals())
+
+	return enum
+# }}}
+
+def FormatToCode(format): # {{{
+	"""
+	This routine takes the format string, and hardcodes it into an integer, which 
+	is passed along the record, in order to identify the nature of the dataset being 
+	sent.
+	"""
+
+	if   strcmpi(format,'Boolean'):
+		code=1
+	elif strcmpi(format,'Integer'):
+		code=2
+	elif strcmpi(format,'Double'):
+		code=3
+	elif strcmpi(format,'String'):
+		code=4
+	elif strcmpi(format,'BooleanMat'):
+		code=5
+	elif strcmpi(format,'IntMat'):
+		code=6
+	elif strcmpi(format,'DoubleMat'):
+		code=7
+	elif strcmpi(format,'MatArray'):
+		code=8
+	elif strcmpi(format,'StringArray'):
+		code=9
+	else:
+		raise InputError('FormatToCode error message: data type not supported yet!')
+
+	return code
+# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/loadmultipleresultsfromcluster.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/loadmultipleresultsfromcluster.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/loadmultipleresultsfromcluster.m	(revision 13101)
@@ -0,0 +1,34 @@
+function md_list=loadmultipleresultsfromcluster(md_list)
+%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
+%
+%   Usage:
+%      md_list=loadresultsfromcluster(md_list);
+
+nummodels=length(md_list);
+
+%Get cluster settings
+cluster=md_list{1}.cluster;
+name=md_list{1}.name;
+cluster_rc_location=which('cluster.rc');
+[codepath,executionpath,login]=ClusterParameters(cluster,cluster_rc_location);
+
+%Remote tar: 
+disp('tarring results');
+issmssh(cluster,['"cd ' executionpath ' && rm -rf file_list.txt ModelResults.tar.gz && find -iname ''*_*vs*.outbin'' > file_list.txt && tar zcvf ModelResults.tar.gz --files-from file_list.txt  && rm -rf file_list.txt "']);
+
+%copy results from cluster to present directory
+scpin(cluster, executionpath, {'ModelResults.tar.gz'});
+
+%untar:
+!tar -zxvf ModelResults.tar.gz
+
+%ok, go through list and load results from disk: 
+for i=1:nummodels,
+	%load  results for this model
+	md_list{i}=loadresultsfromdisk(md_list{i},[md_list{i}.name '.outbin']);
+
+	delete([name '.outbin']);
+end
+
+%erase files 
+delete('ModelResults.tar.gz');
Index: /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.m	(revision 13101)
@@ -0,0 +1,60 @@
+function md=loadresultsfromcluster(md,runtimename)
+%LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
+%
+%   Usage:
+%      md=loadresultsfromcluster(md,runtimename);
+
+%retrieve cluster, to be able to call its methods
+cluster=md.cluster;
+
+if nargin==2,
+	md.private.runtimename=runtimename;
+end
+
+%Download outputs from the cluster
+filelist={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+if md.qmu.isdakota,
+	filelist{end+1}=[md.miscellaneous.name '.qmu.err'];
+	filelist{end+1}=[md.miscellaneous.name '.qmu.out'];
+	if isfield(md.qmu.params,'tabular_graphics_data'),
+		if md.qmu.params.tabular_graphics_data==true,
+			filelist{end+1}='dakota_tabular.dat';
+		end
+	end
+else
+	filelist{end+1}=[md.miscellaneous.name '.outbin'];
+end
+Download(cluster,md.private.runtimename,filelist);
+
+%If we are here, no errors in the solution sequence, call loadresultsfromdisk.
+md=loadresultsfromdisk(md,[md.miscellaneous.name '.outbin']);
+
+%erase the log and output files
+if md.qmu.isdakota,
+	delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.outlog']);
+	delete([['qmu' num2str(feature('GetPid')) '/']  md.miscellaneous.name '.errlog']);
+else
+	delete([md.miscellaneous.name '.outlog']);
+	delete([md.miscellaneous.name '.errlog']);
+	delete([md.miscellaneous.name '.outbin']);
+	if ~ispc,
+		delete([md.private.runtimename '.tar.gz']);
+	end
+end
+
+%erase input file if run was carried out on same platform.
+hostname=oshostname();
+if strcmpi(hostname,cluster.name),
+	if md.qmu.isdakota,
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.bin']);
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.queue']);
+	else
+		delete([md.miscellaneous.name '.bin']);
+		delete([md.miscellaneous.name '.petsc']);
+		if ~ispc,
+			delete([md.miscellaneous.name '.queue']);
+		else
+			delete([md.miscellaneous.name '.bat']);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromcluster.py	(revision 13101)
@@ -0,0 +1,62 @@
+import os
+import platform
+import socket
+from MatlabFuncs import *
+from loadresultsfromdisk import *
+
+def loadresultsfromcluster(md,runtimename=False):
+	"""
+	LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
+ 
+	   Usage:
+	      md=loadresultsfromcluster(md,runtimename);
+	"""
+
+	#retrieve cluster, to be able to call its methods
+	cluster=md.cluster
+
+	if runtimename:
+		md.private.runtimename=runtimename
+
+	#Download outputs from the cluster
+	filelist=[md.miscellaneous.name+'.outlog',md.miscellaneous.name+'.errlog']
+	if md.qmu.isdakota:
+		filelist.append(md.miscellaneous.name+'.qmu.err')
+		filelist.append(md.miscellaneous.name+'.qmu.out')
+		if 'tabular_graphics_data' in md.qmu.params:
+			if md.qmu.params['tabular_graphics_data']:
+				filelist.append('dakota_tabular.dat')
+	else:
+		filelist.append(md.miscellaneous.name+'.outbin')
+	cluster.Download(md.private.runtimename,filelist)
+
+	#If we are here, no errors in the solution sequence, call loadresultsfromdisk.
+	md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
+
+	#erase the log and output files
+	if md.qmu.isdakota:
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.outlog'))
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.errlog'))
+	else:
+		os.remove(md.miscellaneous.name+'.outlog')
+		os.remove(md.miscellaneous.name+'.errlog')
+		os.remove(md.miscellaneous.name+'.outbin')
+		if 'Windows' not in platform.system():
+			os.remove(md.private.runtimename+'.tar.gz')
+
+	#erase input file if run was carried out on same platform.
+	hostname=socket.gethostname().lower().split('.')[0]
+	if strcmpi(hostname,cluster.name):
+		if md.qmu.isdakota:
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.bin'))
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.queue'))
+		else:
+			os.remove(md.miscellaneous.name+'.bin')
+			os.remove(md.miscellaneous.name+'.petsc')
+			if 'Windows' not in platform.system():
+				os.remove(md.miscellaneous.name+'.queue')
+			else:
+				os.remove(md.miscellaneous.name+'.bat')
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.m	(revision 13101)
@@ -0,0 +1,61 @@
+function md=loadresultsfromdisk(md,filename)
+%LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+%
+%   Usage:
+%      md=loadresultsfromdisk(md,filename);
+
+%check number of inputs/outputs
+if ((nargin~=2) | (nargout~=1)),
+	help loadresultsfromdisk;
+	error('loadresultsfromdisk: error message.');
+end
+
+if ~md.qmu.isdakota,
+
+	%Check that file exists
+	if ~exist(filename,'file'),
+		error(['binary file ' filename ' not found.']);
+	end
+
+	%initialize md.results if not a structure yet
+	if ~isstruct(md.results),
+		md.results=struct();
+	end
+
+	%load results onto model
+	structure=parseresultsfromdisk(filename,~md.settings.io_gather);
+	if isempty(fieldnames(structure)),
+		error(['No result found in binary file ' filename '. Check for solution crash.']);
+	end
+	md.results.(structure(1).SolutionType)=structure;
+
+	%recover solution_type from results
+	md.private.solution=structure(1).SolutionType;
+
+	%read log files onto  fields
+	if exist([md.miscellaneous.name '.errlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).errlog=char(textread([md.miscellaneous.name '.errlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).errlog='';
+	end
+
+	if exist([md.miscellaneous.name '.outlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).outlog=char(textread([md.miscellaneous.name '.outlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).outlog='';
+	end
+
+	if ~isempty(md.results.(structure(1).SolutionType)(1).errlog),
+		disp(['loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields']);
+	end
+
+
+%post processes qmu results if necessary
+else
+
+	if isscalar(md.private.solution),
+		md.private.solution=EnumToString(md.private.solution);
+	end
+	md=postqmu(md);
+	cd ..
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/loadresultsfromdisk.py	(revision 13101)
@@ -0,0 +1,61 @@
+import os
+from parseresultsfromdisk import *
+from EnumToString import EnumToString
+
+def loadresultsfromdisk(md,filename):
+	"""
+	LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+ 
+	   Usage:
+	      md=loadresultsfromdisk(md=False,filename=False);
+	"""
+
+	#check number of inputs/outputs
+	if not md or not filename:
+		raise ValueError("loadresultsfromdisk: error message.")
+
+	if not md.qmu.isdakota:
+
+		#Check that file exists
+		if not os.path.exists(filename):
+			raise OSError("binary file '%s' not found." % filename)
+
+		#initialize md.results if not a structure yet
+		if not isinstance(md.results,dict):
+			md.results={}
+
+		#load results onto model
+		structure=parseresultsfromdisk(filename,~md.settings.io_gather)
+		if not len(structure):
+			raise RuntimeError("No result found in binary file '%s'. Check for solution crash." % filename)
+		md.results[structure[1]['SolutionType']]=structure;
+
+		#recover solution_type from results
+		md.private.solution=structure[1]['SolutionType']
+
+		#read log files onto fields
+		if os.path.exists(md.miscellaneous.name+'.errlog'):
+			with open(md.miscellaneous.name+'.errlog','r') as f:
+				md.results[structure[1]['SolutionType']]['errlog']=[line[:-1] for line in f]
+		else:
+			md.results[structure[1]['SolutionType']]['errlog']=[]
+
+		if os.path.exists(md.miscellaneous.name+'.outlog'):
+			with open(md.miscellaneous.name+'.outlog','r') as f:
+				md.results[structure[1]['SolutionType']]['outlog']=[line[:-1] for line in f]
+		else:
+			md.results[structure[1]['SolutionType']]['outlog']=[]
+
+		if len(md.results[structure[1]['SolutionType']]['errlog']):
+			print ("loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields.")
+
+	#post processes qmu results if necessary
+	else:
+
+		if not isinstance(md.private.solution,(str,unicode)):
+			[md.private.solution]=EnumToString(md.private.solution)
+		md=postqmu(md)
+		os.chdir('..')
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/marshall.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/marshall.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/marshall.m	(revision 13101)
@@ -0,0 +1,49 @@
+function marshall(md)
+%MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+%
+%   The routine creates a compatible binary file from @model md
+%   This binary file will be used for parallel runs in JPL-package
+%
+%   Usage:
+%      marshall(md)
+
+disp(['marshalling file ' md.miscellaneous.name '.bin']);
+
+%open file for binary writing
+fid=fopen([ md.miscellaneous.name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' [md.miscellaneous.name '.bin'],' file for binary writing']);
+end
+
+%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
+
+%Go through all model fields: check that it is a class and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be marshalled
+	if ismember(field,{'results' 'radaroverlay' 'solver' 'cluster'  'flaim' 'private'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		error(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Marshall current object
+	%disp(['marshalling ' field '...']);
+	if verLessThan('matlab', '7.6')
+		marshall(md.(field),fid);
+	else
+		md.(field).marshall(fid);
+	end
+end
+
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' [md.miscellaneous.name '.bin']]);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/marshall.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/marshall.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/marshall.py	(revision 13101)
@@ -0,0 +1,49 @@
+from WriteData import *
+from EnumDefinitions import *
+
+def marshall(md):
+	"""
+	MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+
+	   The routine creates a compatible binary file from @model md
+	   This binary file will be used for parallel runs in JPL-package
+
+	   Usage:
+	      marshall(md)
+	"""
+
+	print "marshalling file '%s.bin'." % md.miscellaneous.name
+
+	#open file for binary writing
+	try:
+		fid=open(md.miscellaneous.name+'.bin','wb')
+	except IOError as e:
+		raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name)
+
+	#First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+	WriteData(fid,'enum',MaximumNumberOfEnums(),'data',True,'format','Boolean')
+
+	#Go through all model fields: check that it is a class and call checkconsistency
+	fields=vars(md)
+
+#	for field in fields.iterkeys():
+	for field in ['mesh','mask','geometry','constants','surfaceforcings','basalforcings','materials','friction','flowequation','timestepping','initialization','rifts','debug','verbose','settings','solver','cluster','balancethickness','diagnostic','groundingline','hydrology','prognostic','thermal','steadystate','transient','autodiff','flaim','inversion','qmu','results','radaroverlay','miscellaneous','private']:
+
+		#Some properties do not need to be marshalled
+		if field in ['results','radaroverlay','solver','cluster','flaim','private']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'marshall'):
+			raise TypeError("field '%s' is not an object." % field)
+
+		#Marshall current object
+		print "marshalling %s ..." % field
+		exec("md.%s.marshall(fid)" % field)
+
+	#close file
+	try:
+		fid.close()
+	except IOError as e:
+		raise IOError("marshall error message: could not close file '%s.bin'." % md.miscellaneous.name)
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.m	(revision 13101)
@@ -0,0 +1,212 @@
+function results=parseresultsfromdisk(filename,iosplit)
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdisk(filename,iosplit)
+
+if iosplit,
+	results=parseresultsfromdiskiosplit(filename);
+else
+	results=parseresultsfromdiskioserial(filename);
+end
+
+%process patch if necessary
+results=MatlabProcessPatch(results);
+
+function results=parseresultsfromdiskioserial(filename) % {{{
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskioserial(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%Read fields until the end of the file.
+result=ReadData(fid);
+while ~isempty(result), 
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if (length(results)>=result.step & isfield(results,result.fieldname) & ~strcmp(result.fieldname,'SolutionType')),
+			results(result.step).(result.fieldname)=[ results(result.step).(result.fieldname); result.field];
+	else
+		results(result.step).(result.fieldname)=result.field;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+fclose(fid);
+% }}}
+function results=parseresultsfromdiskiosplit(filename) % {{{
+%PARSERESULTSFROMDISKIOSPLIT - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskiosplit(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%if we have done split I/O, ie, we have results that are fragmented across patches, 
+%do a first pass, and figure out the structure of results
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		results(result.step).(result.fieldname)=[0 result.N];
+	else
+		results(result.step).(result.fieldname)=NaN;
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%do a second pass, and figure out the size of the patches
+fseek(fid,0,-1); %rewind
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		patchdimensions=results(result.step).(result.fieldname);
+		results(result.step).(result.fieldname)=[patchdimensions(1)+result.M result.N];
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%allocate patches
+for i=1:length(results),
+	results(i).Patch=zeros(results(i).Patch(1),results(i).Patch(2));
+	results(i).counter=1; %use to index into the patch
+end
+
+%third pass, this time to read the real information
+fseek(fid,0,-1); %rewind
+result=ReadData(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		counter=results(result.step).counter;
+		counter2=counter+size(result.field,1)-1;
+		results(result.step).(result.fieldname)(counter:counter2,:)=result.field;
+
+		%increment counter: 
+		results(result.step).counter=counter2+1;
+	else
+		results(result.step).(result.fieldname)=result.field;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+%close file
+fclose(fid);
+	% }}}
+function result=ReadData(fid) % {{{
+%READDATA - ...
+%
+%   Usage:
+%      field=ReadData(fid)
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	if type==1,
+		field=fread(fid,M,'double');
+	elseif type==2,
+		field=fread(fid,M,'char');
+		field=char(field(1:end-1)');
+	elseif type==3,
+		N=fread(fid,1,'int');
+		field=transpose(fread(fid,[N M],'double'));
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.field=field;
+end
+% }}}
+function result=ReadDataDimensions(fid) % {{{
+%READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+%
+%   Usage:
+%      field=ReadDataDimensions(fid)
+
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	N=1; %default
+	if type==1,
+		fseek(fid,M*8,0);
+	elseif type==2,
+		fseek(fid,M,0);
+	elseif type==3,
+		N=fread(fid,1,'int');
+		fseek(fid,N*M*8,0);
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.M=M;
+	result.N=N;
+end
+% }}}
Index: /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/parseresultsfromdisk.py	(revision 13101)
@@ -0,0 +1,235 @@
+import struct
+import numpy
+from MatlabFuncs import *
+from MatlabProcessPatch import *
+
+def parseresultsfromdisk(filename,iosplit):
+	"""
+	PARSERESULTSFROMDISK - ...
+
+	   Usage:
+	      results=parseresultsfromdisk(filename,iosplit)
+	"""
+
+	if iosplit:
+		results=parseresultsfromdiskiosplit(filename)
+	else:
+		results=parseresultsfromdiskioserial(filename)
+
+	#process patch if necessary
+	results=MatlabProcessPatch(results)
+
+	return results
+
+def parseresultsfromdiskioserial(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISK - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskioserial(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results={}
+
+	#Read fields until the end of the file.
+	result=ReadData(fid)
+	while result:
+		#Get time and step
+		if result['step'] not in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+	
+		#Add result
+		if result['step'] in results and \
+		   result['fieldname'] in results[result['step']] and \
+		   not strcmp(result['fieldname'],'SolutionType'):
+			results[result['step']][result['fieldname']]=numpy.concatenate((results[result['step']][result['fieldname']],result['field']),axis=0)
+		else:
+			results[result['step']][result['fieldname']]=result['field']
+
+		#read next result
+		result=ReadData(fid)
+
+	fid.close()
+
+	return results
+	# }}}
+
+def parseresultsfromdiskiosplit(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISKIOSPLIT - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskiosplit(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results={}
+
+	#if we have done split I/O, ie, we have results that are fragmented across patches, 
+	#do a first pass, and figure out the structure of results
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#Get time and step
+		if result['step'] not in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			results[result['step']][result['fieldname']]=[0,result['N']]
+		else:
+			results[result['step']][result['fieldname']]=float('NaN')
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#do a second pass, and figure out the size of the patches
+	fid.seek(0)    #rewind
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			patchdimensions=results[result['step']][result['fieldname']]
+			results[result['step']][result['fieldname']]=[patchdimensions[0]+result['M'],result['N']]
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#allocate patches
+	for result in results.itervalues():
+		if 'Patch' in result:
+			result['Patch']=numpy.zeros(shape=(result['Patch'][0],result['Patch'][1]),dtype=float)
+			result['counter']=0    #use to index into the patch
+
+	#third pass, this time to read the real information
+	fid.seek(0)    #rewind
+	result=ReadData(fid)
+	while result:
+
+		#Get time and step
+		if result['step'] not in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			counter=results[result['step']]['counter']
+			counter2=counter+result['field'].shape[0]-1
+			results[result['step']][result['fieldname']][counter:counter2,:]=result['field']
+
+			#increment counter: 
+			results[result['step']]['counter']=counter2+1
+		else:
+			results[result['step']][result['fieldname']]=result['field']
+
+		#read next result
+		result=ReadData(fid)
+
+	#close file
+	fid.close()
+
+	return results
+	# }}}
+
+def ReadData(fid):    # {{{
+	"""
+	READDATA - ...
+	 
+	    Usage:
+	       field=ReadData(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		if   type==1:
+			field=numpy.array(struct.unpack('%dd' % M,fid.read(M*struct.calcsize('d'))),dtype=float)
+		elif type==2:
+			field=struct.unpack('%ds' % M,fid.read(M))[0][:-1]
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+#			field=transpose(fread(fid,[N M],'double'));
+			field=numpy.zeros(shape=(M,N),dtype=float)
+			for i in xrange(M):
+				field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d')))
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		result={}
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['field']=field
+
+	except struct.error as e:
+		result={}
+
+	return result
+	# }}}
+
+def ReadDataDimensions(fid):    # {{{
+	"""
+	READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+	 
+	    Usage:
+	       field=ReadDataDimensions(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		N=1    #default
+		if   type==1:
+			fid.seek(M*8,1)
+		elif type==2:
+			fid.seek(M,1)
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+			fid.seek(N*M*8,1)
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		result={}
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['M']=M
+		result['N']=N
+
+	except struct.error as e:
+		result={}
+
+	return result
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.m	(revision 13101)
@@ -0,0 +1,39 @@
+function outoptions=process_solve_options(options)
+%DEFAULT_SOLVE_OPTIONS - set up default options for solve phase
+%
+%   Usage:
+%      options=process_solve_options(options)
+%
+%   See also: SOLVE
+
+%solution_type: check on this option, error out otherwise
+solution_type=getfieldvalue(options,'solution_type');
+if ~ismember(solution_type,[DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),...
+		SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),...
+		BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum()]),
+	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
+end
+outoptions.solution_type=solution_type;
+
+outoptions.upload=getfieldvalue(options,'upload','off');
+outoptions.batch=getfieldvalue(options,'batch','no');
+outoptions.loadonly=getfieldvalue(options,'loadonly',false);
+outoptions.directory=getfieldvalue(options,'directory','');
+
+%  process qmu arguments
+outoptions.qmudir=getfieldvalue(options,'qmudir',['qmu' num2str(feature('GetPid'))]);  % qmudir =['qmu_' datestr(now,'yyyymmdd_HHMMSS')];
+outoptions.qmufile=getfieldvalue(options,'qmufile','qmu');% qmufile cannot be changed unless ????script.sh is also changed
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','n');
+outoptions.ivar=getfieldvalue(options,'ivar',1);
+outoptions.iresp=getfieldvalue(options,'iresp',1);
+outoptions.imethod=getfieldvalue(options,'imethod',1);
+outoptions.iparams=getfieldvalue(options,'iparams',1);
+outoptions.runmpi=getfieldvalue(options,'runmpi',false);
+
+%  process flaim arguments
+outoptions.fmdir=getfieldvalue(options,'fmdir',['fm' num2str(feature('GetPid'))]);
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','y');
+outoptions.latsgn=getfieldvalue(options,'latsgn',0);
+outoptions.cmap=getfieldvalue(options,'cmap',[]);
Index: /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/process_solve_options.py	(revision 13101)
@@ -0,0 +1,49 @@
+import os
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def process_solve_options(options):
+	"""
+	DEFAULT_SOLVE_OPTIONS - set up default options for solve phase
+ 
+	   Usage:
+	      options=process_solve_options(options)
+ 
+	   See also: SOLVE
+	"""
+
+	outoptions={}
+
+	#solution_type: check on this option, error out otherwise
+	solution_type=options.getfieldvalue('solution_type')
+	if solution_type not in (DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),\
+			SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),\
+			BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum()):
+		raise ValueError("process_solve_options error message: solution_type '%s' not supported yet!" % EnumToString(solution_type)[0])
+	outoptions['solution_type']=solution_type
+
+	outoptions['upload']=options.getfieldvalue('upload','off')
+	outoptions['batch']=options.getfieldvalue('batch','no')
+	outoptions['loadonly']=options.getfieldvalue('loadonly',False)
+	outoptions['directory']=options.getfieldvalue('directory','')
+
+	#  process qmu arguments
+	outoptions['qmudir']=options.getfieldvalue('qmudir','qmu'+str(os.getpid()))
+	outoptions['qmufile']=options.getfieldvalue('qmufile','qmu')    # qmufile cannot be changed unless ????script.sh is also changed
+	outoptions['overwrite']=options.getfieldvalue('overwrite','n')
+	outoptions['keep']=options.getfieldvalue('keep','n')
+	outoptions['ivar']=options.getfieldvalue('ivar',1)
+	outoptions['iresp']=options.getfieldvalue('iresp',1)
+	outoptions['imethod']=options.getfieldvalue('imethod',1)
+	outoptions['iparams']=options.getfieldvalue('iparams',1)
+	outoptions['runmpi']=options.getfieldvalue('runmpi',False)
+
+	#  process flaim arguments
+	outoptions['fmdir']=options.getfieldvalue('fmdir','fm'+str(os.getpid()))
+	outoptions['overwrite']=options.getfieldvalue('overwrite','n')
+	outoptions['keep']=options.getfieldvalue('keep','y')
+	outoptions['latsgn']=options.getfieldvalue('latsgn',0)
+	outoptions['cmap']=options.getfieldvalue('cmap',[])
+
+	return outoptions
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/solve.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/solve.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/solve.m	(revision 13101)
@@ -0,0 +1,121 @@
+function md=solve(md,solutionenum,varargin)
+%SOLVE - apply solution sequence for this model
+%
+%   Usage:
+%      md=solve(md,solutionenum,varargin)
+%      where varargin is a lit of paired arguments of string OR enums
+%
+%   solution types available comprise:
+%		 - DiagnosticSolutionEnum
+%		 - PrognosticSolutionEnum
+%		 - ThermalSolutionEnum
+%		 - SteadystateSolutionEnum
+%		 - TransientSolutionEnum...
+%		 - BalancethicknessSolutionEnum
+%		 - BedSlopeSolutionEnum
+%		 - SurfaceSlopeSolutionEnum
+%		 - HydrologySolutionEnum
+%		 - FlaimSolutionEnum
+%
+%  extra options:
+%      - loadonly : does not solve. only load results
+%
+%   Examples:
+%      md=solve(md,DiagnosticSolutionEnum);
+
+%recover and process solve options
+options=pairoptions(varargin{:},'solution_type',solutionenum);
+options=process_solve_options(options);
+
+%recover some fields
+md.private.solution=options.solution_type;
+cluster=md.cluster;
+
+%check model consistency
+disp('checking model consistency');
+if (solutionenum == FlaimSolutionEnum())
+	md.private.isconsistent=true;
+	md=checkconsistency(md.mesh,md,solutionenum);
+	md=checkconsistency(md.flaim,md,solutionenum);
+	if md.private.isconsistent==false,
+		error('Model not consistent, see messages above');
+	end
+else
+	ismodelselfconsistent(md),
+end
+
+%First, build a runtime name that is unique
+c=clock;
+md.private.runtimename=sprintf('%s-%02i-%02i-%04i-%02i-%02i-%02i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
+
+%if running qmu analysis, some preprocessing of dakota files using models
+%fields needs to be carried out. 
+if md.qmu.isdakota,
+	md=preqmu(md,options);
+end
+
+%flaim analysis
+if (options.solution_type == FlaimSolutionEnum())
+	md=flaim_sol(md,options);
+	md.private.solution=EnumToString(options.solution_type);
+	return;
+end
+
+%Do we load results only?
+if options.loadonly,  
+	md=loadresultsfromcluster(md);
+	return;
+end
+
+%we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
+if ~ispetsc(),
+	disp('PETSC support not included, running on 1 cpu only!');
+	cluster.np=1;
+end
+
+
+%Write all input files
+marshall(md);                                          % bin file
+PetscFile(md.solver,[md.miscellaneous.name '.petsc']); % petsc file
+BuildQueueScript(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof); % queue file
+
+
+%Stop here if batch mode
+if strcmpi(options.batch,'yes')
+	disp('batch mode requested: not launching job interactively');
+	disp('launch solution sequence on remote cluster by hand');
+	return;
+end
+
+%Launch job
+modelname = md.miscellaneous.name;
+filelist  = {[modelname '.bin '] [modelname '.petsc '] [modelname '.queue ']};
+if md.qmu.isdakota,
+	filelist{end+1} = [modelname '.qmu.in'];
+end
+LaunchQueueJob(cluster,md.miscellaneous.name,md.private.runtimename,filelist);
+
+%did we even try to run? if so, wait on lock
+if strcmpi(options.upload,'on'),
+	disp('solve done uploading test decks');
+	return;
+end
+
+%wait on lock
+if md.settings.waitonlock>0,
+	%we wait for the done file
+	islock=waitonlock(md);
+	if islock==0, %no results to be loaded
+		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+	else          %load results
+		disp('loading results from cluster');
+		md=loadresultsfromcluster(md);
+	end
+end
+
+%post processes qmu results if necessary
+if md.qmu.isdakota,
+	if ~strncmpi(options.keep,'y',1)
+		system(['rm -rf qmu' num2str(feature('GetPid'))]);
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/solve.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/solve.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/solve.py	(revision 13101)
@@ -0,0 +1,124 @@
+import datetime
+import os
+import shutil
+from pairoptions import *
+from process_solve_options import *
+from EnumDefinitions import *
+from EnumToString import EnumToString
+from ismodelselfconsistent import *
+from marshall import *
+from ispetsc import *
+from waitonlock import *
+from loadresultsfromcluster import *
+
+def solve(md,solutionenum,*args):
+	"""
+	SOLVE - apply solution sequence for this model
+ 
+	   Usage:
+	      md=solve(md,solutionenum,varargin)
+	      where varargin is a list of paired arguments of string OR enums
+ 
+	   solution types available comprise:
+	      - DiagnosticSolutionEnum
+	      - PrognosticSolutionEnum
+	      - ThermalSolutionEnum
+	      - SteadystateSolutionEnum
+	      - TransientSolutionEnum...
+	      - BalancethicknessSolutionEnum
+	      - BedSlopeSolutionEnum
+	      - SurfaceSlopeSolutionEnum
+	      - HydrologySolutionEnum
+	      - FlaimSolutionEnum
+ 
+	   extra options:
+	      - loadonly : does not solve. only load results
+ 
+	   Examples:
+	      md=solve(md,DiagnosticSolutionEnum);
+	"""
+
+	#recover and process solve options
+	options=pairoptions('solution_type',solutionenum,*args)
+	options=process_solve_options(options)
+
+	#recover some fields
+	md.private.solution=options['solution_type']
+	cluster=md.cluster
+
+	#check model consistency
+	print "checking model consistency"
+	if solutionenum == FlaimSolutionEnum():
+		md.private.isconsistent=True
+		md.mesh.checkconsistency(md,solutionenum)
+		md.flaim.checkconsistency(md,solutionenum)
+		if not md.private.isconsistent:
+			raise RuntimeError("Model not consistent, see messages above.")
+	else:
+		ismodelselfconsistent(md)
+
+	#First, build a runtime name that is unique
+	c=datetime.datetime.now()
+	md.private.runtimename="%s-%02i-%02i-%04i-%02i-%02i-%02i-%i" % (md.miscellaneous.name,c.month,c.day,c.year,c.hour,c.minute,c.second,os.getpid())
+
+	#if running qmu analysis, some preprocessing of dakota files using models
+	#fields needs to be carried out. 
+	if md.qmu.isdakota:
+		md=preqmu(md,options)
+
+	#flaim analysis
+	if options['solution_type'] == FlaimSolutionEnum():
+		md=flaim_sol(md,options)
+		[md.private.solution]=EnumToString(options['solution_type'])
+		return md
+
+	#Do we load results only?
+	if options['loadonly']:  
+		md=loadresultsfromcluster(md)
+		return md
+
+	#Write all input files
+	marshall(md)                                           # bin file
+	md.solver.PetscFile(md.miscellaneous.name+'.petsc')    # petsc file
+	cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof)    # queue file
+
+	#we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
+	if not ispetsc():
+		print "PETSC support not included, running on 1 cpu only!"
+		cluster.np=1
+
+	#Stop here if batch mode
+	if strcmpi(options['batch'],'yes'):
+		print 'batch mode requested: not launching job interactively'
+		print 'launch solution sequence on remote cluster by hand'
+		return md
+
+	#Launch job
+	modelname = md.miscellaneous.name
+	filelist  = [modelname+'.bin ',modelname+'.petsc ',modelname+'.queue ']
+	if md.qmu.isdakota:
+		filelist.append(modelname+'.qmu.in')
+	cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist)
+
+	#did we even try to run? if so, wait on lock
+	if strcmpi(options['upload'],'on'):
+		print 'solve done uploading test decks'
+		return md
+
+	#wait on lock
+	if md.settings.waitonlock>0:
+		#we wait for the done file
+		islock=waitonlock(md)
+		if islock==0:    #no results to be loaded
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+		else:            #load results
+			print 'loading results from cluster'
+			md=loadresultsfromcluster(md)
+
+	#post processes qmu results if necessary
+	if md.qmu.isdakota:
+		if not strncmpi(options['keep'],'y',1):
+			shutil.rmtree('qmu'+str(os.getpid()))
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.m	(revision 13101)
@@ -0,0 +1,58 @@
+function flag=waitonlock(md)
+%WAITONLOCK - wait for a file
+%
+%   This routine will return when a file named 'filename' is written to disk.
+%   If the time limit given in input is exceeded, return 0
+%
+%   Usage:
+%      flag=waitonlock(md)
+
+%Get filename (lock file) and options
+executionpath=md.cluster.executionpath;
+cluster=md.cluster.name;
+login=md.cluster.login;
+port=md.cluster.port;
+timelimit=md.settings.waitonlock;
+filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
+
+%waitonlock will work if the lock is on the same machine only: 
+if ~strcmpi(oshostname(),cluster),
+
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+		flag=0;
+	else
+		flag=1;
+	end
+
+%job is running on the same machine
+else
+
+	if ismember('interactive',properties(md.cluster)) & md.cluster.interactive
+		%We are in interactive mode, no need to check for job completion
+		flag=1;
+		return;
+	end
+	%initialize time and file presence test flag
+	time=0; ispresent=0;
+	disp(['waiting for ' filename ' hold on... (Ctrl+C to exit)'])
+
+	%loop till file .lock exist or time is up
+	while (ispresent==0 & time<timelimit)
+		ispresent=exist(filename,'file');
+		pause(1);
+		time=time+1/60;
+	end
+
+	%build output
+	if (time>timelimit),
+		disp('Time limit exceeded. Increase md.settings.waitonlock');
+		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+		error(['waitonlock error message: time limit exceeded']);
+		flag=0;
+	else
+		flag=1;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solve/waitonlock.py	(revision 13101)
@@ -0,0 +1,64 @@
+import os
+import socket
+import time
+from MatlabFuncs import *
+
+def waitonlock(md):
+	"""
+	WAITONLOCK - wait for a file
+ 
+	   This routine will return when a file named 'filename' is written to disk.
+	   If the time limit given in input is exceeded, return 0
+ 
+	   Usage:
+	      flag=waitonlock(md)
+	"""
+
+	#Get filename (lock file) and options
+	executionpath=md.cluster.executionpath
+	cluster=md.cluster.name
+	login=md.cluster.login
+	port=md.cluster.port
+	timelimit=md.settings.waitonlock
+	filename=os.path.join(executionpath,md.private.runtimename,md.miscellaneous.name+'.lock')
+
+	#waitonlock will work if the lock is on the same machine only: 
+	if not strcmpi(socket.gethostname().lower().split('.')[0],cluster):
+
+		print 'solution launched on remote cluster. log in to detect job completion.'
+		choice=raw_input('Is the job successfully completed? (y/n) ')
+		if not strcmp(choice,'y'): 
+			print 'Results not loaded... exiting' 
+			flag=0
+		else:
+			flag=1
+
+	#job is running on the same machine
+	else:
+
+		if 'interactive' in vars(md.cluster) and md.cluster.interactive:
+			#We are in interactive mode, no need to check for job completion
+			flag=1
+			return flag
+		#initialize time and file presence test flag
+		etime=0
+		ispresent=0
+		print "waiting for '%s' hold on... (Ctrl+C to exit)" % filename
+
+		#loop till file .lock exist or time is up
+		while ispresent==0 and etime<timelimit:
+			ispresent=os.path.exist(filename)
+			time.sleep(1)
+			etime+=1/60
+
+		#build output
+		if etime>timelimit:
+			print 'Time limit exceeded. Increase md.settings.waitonlock'
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+			raise RuntimeError('waitonlock error message: time limit exceeded.')
+			flag=0
+		else:
+			flag=1
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.m	(revision 13101)
@@ -0,0 +1,18 @@
+function asm=asmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method petsc options
+%
+%   Usage:
+%      options=asmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+asm=struct();
+
+%default asm options
+asm.mat_type=getfieldvalue(options,'mat_type','aij');
+asm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+asm.pc_type=getfieldvalue(options,'pc_type','asm');
+asm.sub_pc_type=getfieldvalue(options,'sub_pc_type','lu');
+asm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+asm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+asm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-30);
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/asmoptions.py	(revision 13101)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def asmoptions(*args):
+	#ASMOPTIONS - return ASM petsc options
+	#
+	#   Usage:
+	#      options=asmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.m	(revision 13101)
@@ -0,0 +1,18 @@
+function iluasm=iluasmoptions(varargin)
+%ILUASMOPTIONS - 
+%
+%   Usage:
+%      options=iluasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+iluasm=struct();
+
+%default iluasm options
+iluasm.mat_type=getfieldvalue(options,'mat_type','aij');
+iluasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+iluasm.pc_type=getfieldvalue(options,'pc_type','asm');
+iluasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','ilu');
+iluasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',5);
+iluasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+iluasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/iluasmoptions.py	(revision 13101)
@@ -0,0 +1,25 @@
+from pairoptions import *
+
+def iluasmoptions(*args):
+	"""
+	ILUASMOPTIONS - 
+
+	   Usage:
+	      options=iluasmoptions;
+	"""
+			 
+	#retrieve options provided in varargin
+	options=pairoptions(*args)
+	iluasm={}
+
+	#default iluasm options
+	iluasm['mat_type']=options.getfieldvalue('mat_type','aij')
+	iluasm['ksp_type']=options.getfieldvalue('ksp_type','gmres')
+	iluasm['pc_type']=options.getfieldvalue('pc_type','asm')
+	iluasm['sub_pc_type']=options.getfieldvalue('sub_pc_type','ilu')
+	iluasm['pc_asm_overlap']=options.getfieldvalue('pc_asm_overlap',5)
+	iluasm['ksp_max_it']=options.getfieldvalue('ksp_max_it',100)
+	iluasm['ksp_rtol']=options.getfieldvalue('ksp_rtol',1e-15)
+
+	return iluasm
+
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.m	(revision 13101)
@@ -0,0 +1,18 @@
+function jacobiasm=jacobiasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobiasm=struct();
+
+%default jacobiasm options
+jacobiasm.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobiasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+jacobiasm.pc_type=getfieldvalue(options,'pc_type','asm');
+jacobiasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','jacobi');
+jacobiasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+jacobiasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobiasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/jacobiasmoptions.py	(revision 13101)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def jacobiasmoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobiasmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.m	(revision 13101)
@@ -0,0 +1,15 @@
+function jacobicg=jacobiacgoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobicg=struct();
+
+%default jacobiasm options
+jacobicg.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobicg.ksp_type=getfieldvalue(options,'ksp_type','cg');
+jacobicg.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobicg.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/jacobicgoptions.py	(revision 13101)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def jacobicgoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobicgoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.m	(revision 13101)
@@ -0,0 +1,12 @@
+function maltab=matlaboptions(varargin)
+%MATLABOPTIONS - return Matlab petsc options
+%
+%   Usage:
+%      options=matlaboptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+maltab=struct();
+
+%default matlab options
+maltab.ksp_type='matlab';
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/matlaboptions.py	(revision 13101)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def matlaboptions(*args):
+	#MATLABOPTIONS - return Matlab petsc options
+	#
+	#   Usage:
+	#      options=matlaboptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['ksp_type','matlab']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.m	(revision 13101)
@@ -0,0 +1,27 @@
+function mumps=mumpsoptions(varargin)
+%MUMPSOPTIONS - return MUMPS direct solver  petsc options
+%
+%   Usage:
+%      options=mumpsoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+mumps=struct();
+
+%default mumps options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	mumps.mat_type=getfieldvalue(options,'mat_type','aijmumps');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+end
+if PETSC_VERSION==3,
+	mumps.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.pc_factor_mat_solver_package=getfieldvalue(options,'pc_factor_mat_solver_package','mumps');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/mumpsoptions.py	(revision 13101)
@@ -0,0 +1,33 @@
+from pairoptions import *
+from petscversion import *
+
+def mumpsoptions(*args):
+	"""
+	MUMPSOPTIONS - return MUMPS direct solver  petsc options
+
+	   Usage:
+	      options=mumpsoptions;
+	"""
+
+	#retrieve options provided in varargin
+	options=pairoptions(*args)
+	mumps={}
+
+	#default mumps options
+	PETSC_VERSION=petscversion()
+	if PETSC_VERSION==2:
+		mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+	if PETSC_VERSION==3:
+		mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+
+	return mumps
+
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.m	(revision 13101)
@@ -0,0 +1,16 @@
+function sor=soroptions(varargin)
+%SOROPTIONS - return Relaxation Solver petsc options
+%
+%   Usage:
+%      options=soroptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+sor=struct();
+
+%default sor options
+sor.mat_type=getfieldvalue(options,'mat_type','aij');
+sor.ksp_type=getfieldvalue(options,'ksp_type','cg');
+sor.pc_type=getfieldvalue(options,'pc_type','sor');
+sor.pc_sor_omega=getfieldvalue(options,'pc_sor_omega',1.1);
+sor.pc_sor_its=getfieldvalue(options,'pc_sor_its',2);
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/soroptions.py	(revision 13101)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def soroptions(*args):
+	#SOROPTIONS - return Relaxation Solver petsc options
+	#
+	#   Usage:
+	#      options=soroptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.m	(revision 13101)
@@ -0,0 +1,28 @@
+function stokes=stokesoptions(varargin)
+%STOKESOPTIONS - return STOKES multi-physics solver petsc options
+%
+%   Usage:
+%      options=stokesoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+stokes=struct();
+
+%default stokes options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	error('stokesoptions error message: multi-physics options not supported in Petsc 2');
+end
+if PETSC_VERSION==3,
+	stokes.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	stokes.ksp_max_it=getfieldvalue(options,'ksp_max_it',1000);
+	stokes.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+	stokes.pc_type=getfieldvalue(options,'pc_type','fieldsplit');
+	stokes.pc_field_split_type=getfieldvalue(options,'pc_field_split_type','schur');
+	stokes.fieldsplit_0_pc_type=getfieldvalue(options,'fieldsplit_0_pc_type','hypre');
+	stokes.fieldsplit_0_ksp_type=getfieldvalue(options,'fieldsplit_0_ksp_type','gmres');
+	stokes.fieldsplit_0_pc_hypre_type=getfieldvalue(options,'fieldsplit_0_pc_hypre_type','boomerang');
+	stokes.fieldsplit_1_pc_type=getfieldvalue(options,'fieldsplit_1_pc_type','jacobi');
+	stokes.fieldsplit_1_ksp_type=getfieldvalue(options,'fieldsplit_1_ksp_type','preonly');
+	stokes.issm_option_solver=getfieldvalue(options,'issm_option_solver','stokes');
+end
Index: /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.py	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/solvers/stokesoptions.py	(revision 13101)
@@ -0,0 +1,40 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def stokesoptions(*args):
+	#STOKESOPTIONS - return STOKES multi-physics solver petsc options
+	#
+	#   Usage:
+	#      options=stokesoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+
+
+	#default stokes options
+	PETSC_VERSION=petscversion()
+
+	if PETSC_VERSION==2:
+		raise RuntimeError('stokesoptions error message: multi-physics options not supported in Petsc 2')
+	if PETSC_VERSION==3:
+		options=[['mat_type','mpiaij'],['ksp_max_it',1000],['ksp_type','gmres'],['pc_type','fieldsplit'],['pc_field_split_type','schur'],\
+	['fieldsplit_0_pc_type','hypre'],['fieldsplit_0_ksp_type','gmres'],['fieldsplit_0_pc_hypre_type','boomerang'],\
+	['fieldsplit_1_pc_type','jacobi'],['fieldsplit_1_ksp_type','preonly'],['issm_option_solver','stokes']]
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-damage/src/m/string/ddewhite.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/ddewhite.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/ddewhite.m	(revision 13101)
@@ -0,0 +1,30 @@
+function sout = ddewhite(s)
+%DDEWHITE Double dewhite. Strip both leading and trailing whitespace.
+%
+%   DDEWHITE(S) removes leading and trailing white space and any null
+%   characters from the string S.  A null character is one that has an absolute
+%   value of 0.
+%
+%   See also DEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:57 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error('Input must be a string (char array).');
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(min(c) : max(c));
+   else
+      sout = s(:, min(c) : max(c));
+   end
Index: /issm/branches/trunk-jpl-damage/src/m/string/dewhite.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/dewhite.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/dewhite.m	(revision 13101)
@@ -0,0 +1,30 @@
+function sout = dewhite(s)
+%DEWHITE Dewhite. Strip trailing whitespace.
+%
+%   DEWHITE(S) removes leading and trailing white space and any null characters
+%   from the string S.  A null character is one that has an absolute value of
+%   0.
+%
+%   See also DDEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:52 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error( 'Input must be a string (char array).' );
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(1:max(c));
+   else
+      sout = s(:,1:max(c));
+   end
Index: /issm/branches/trunk-jpl-damage/src/m/string/discardnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/discardnum.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/discardnum.m	(revision 13101)
@@ -0,0 +1,14 @@
+function string2=discardnum(string)
+%DISCARDNUM -  ??????
+%
+%   Usage:
+%      string2=discardnum(string)
+
+string2=string;
+
+for i=1:length(string),
+	if (((string(i)-0) <=57) & ((string(i)-0) >=48)),
+		string2=string(1:i-1);
+		break;
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/string/ismemberi.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/ismemberi.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/ismemberi.m	(revision 13101)
@@ -0,0 +1,26 @@
+function flag=ismemberi(string,list),
+%ISMEMBERI - return 1 if a string belongs to a list (case insensitive)
+%
+%   same function as Matlab's ismember except that it
+%   is case insensitive
+%
+%   Usage:
+%      flag=ismemberi(string,list);
+%
+%   Example:
+%      flag=ismemberi('test','{'test1','test2','test3'});
+
+if ~iscell(list)
+	error('ismemberi error message: the list of string must be a cell!')
+end
+
+%initialize output
+flag=0;
+
+%go through the list
+for i=1:length(list),
+	if strcmpi(string,list{i}),
+		flag=i;
+		return
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/string/issmprintf.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/issmprintf.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/issmprintf.m	(revision 13101)
@@ -0,0 +1,13 @@
+function issmprintf(flag,format,varargin)
+%ISSMPRINTF -  display string in solution sequences. wrapper to disp and sprintf.  
+%
+%   Usage:
+%      issmprintf(flag,format,string)
+%      flag can be used to switch display on and off
+%
+%   Example:
+%      issmprintf(1,'%s\n','string to display');
+	
+if flag,
+	disp(sprintf(format,varargin{:}));
+end
Index: /issm/branches/trunk-jpl-damage/src/m/string/strsplit.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/strsplit.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/strsplit.m	(revision 13101)
@@ -0,0 +1,91 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   This function should be used to split a string of delimiter separated
+%   values.  If all values are numerical values the returned matrix is a
+%   double array but if there is one non numerical value a cell array is
+%   returned.  You can check this with the iscell() function.
+%   inpstr: string containing delimiter separatede numerical values, eg
+%           3498,48869,23908,34.67
+%   Output: An x by 1 matrix containing the splitted values
+%   Delimiter: optional, if omitted the delimiter is , (comma)
+%
+%   Usage:
+%      output = strsplit(inpstr[,delimiter])
+%
+
+%   mailto:    gie.spaepen@ua.ac.be
+
+
+
+%Check input arguments
+if(nargin < 1)
+    error('There is no argument defined');
+else
+    if(nargin == 1)
+        strdelim = ',';
+        %Verbose off!! disp 'Delimiter set to ,';
+    else
+        strdelim = delimiter;
+    end
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,strdelim);
+if size(idx) == 0
+    disp 'No delimiter in string, inputString is returned';
+    splittedstring = inpstr;
+else
+    %Define size of the indices
+    sz = size(idx,2);
+    %Define splittedstring
+    tempsplit = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        %Define standard start and stop positions for the start position,
+        %choose 1 as startup position because otherwise you get an array
+        %overflow, for the endposition you can detemine it from the
+        %delimiter position
+        strtpos = 1;
+        endpos = idx(i)-1;
+        %If i is not the beginning of the string get it from the delimiter
+        %position
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        %If i is equal to the number of delimiters get the last element
+        %first by determining the lengt of the string and then replace the
+        %endpos back to a standard position
+        if i == sz
+            endpos = size(inpstr,2); 
+            tempsplit(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        %Add substring to output: splittedstring a cell array
+        tempsplit(i) = {inpstr(strtpos : endpos)};   
+    end
+    %Flag 
+    isallnums = 1;
+    %Check is there are NaN values if matrix elements are converted to
+    %doubles
+    for i = 1:size(tempsplit,2)
+        tempdouble = str2double(tempsplit(i));
+        if(isnan(tempdouble))
+            isallnums = 0;
+        end
+    end
+    %If isallnums = 1 then return a double array otherwise return a cell
+    %array
+    if(isallnums == 1)
+        for i = 1:size(tempsplit,2)
+            splittedstring(i) = str2double(tempsplit(i));
+        end
+    else
+        splittedstring = tempsplit;
+    end
+    
+        
+end
Index: /issm/branches/trunk-jpl-damage/src/m/string/strsplit_strict.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/string/strsplit_strict.m	(revision 13101)
+++ /issm/branches/trunk-jpl-damage/src/m/string/strsplit_strict.m	(revision 13101)
@@ -0,0 +1,37 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   Usage:
+%      output = strsplit_strict(inpstr,delimiter)
+
+
+%Check input arguments
+if(nargin ~= 2)
+    error('There is no argument defined');
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,delimiter);
+if size(idx) == 0
+    splittedstring = {inpstr};
+else
+    sz = size(idx,2);
+    splittedstring = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        strtpos = 1;
+        endpos = idx(i)-1;
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        if i == sz
+            endpos = size(inpstr,2); 
+            splittedstring(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        splittedstring(i) = {inpstr(strtpos : endpos)};   
+    end
+end
Index: /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13101)
@@ -34,8 +34,8 @@
 
 	/*Check inputs*/
-	if(nels<0) _error2_("Number of elements must be positive, check index number of lines");
-	if(nods<0) _error2_("Number of nods must be positive, check x and y sizes");
-	if(test1!=3) _error2_("index should have 3 columns");
-	if(test2!=nods) _error2_("x and y do not have the same length");
+	if(nels<0) _error_("Number of elements must be positive, check index number of lines");
+	if(nods<0) _error_("Number of nods must be positive, check x and y sizes");
+	if(test1!=3) _error_("index should have 3 columns");
+	if(test2!=nods) _error_("x and y do not have the same length");
 
 	/* Run core computations: */
Index: /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 13101)
@@ -32,7 +32,7 @@
 
 	/*Check inputs*/
-	if(y_rows!=nods)         _error2_("x and y do not have the same length");
-	if(x_cols>1 || y_cols>1) _error2_("x and y should have only one column");
-	if(nods<3)               _error2_("At least 3 points are required");
+	if(y_rows!=nods)         _error_("x and y do not have the same length");
+	if(x_cols>1 || y_cols>1) _error_("x and y should have only one column");
+	if(nods<3)               _error_("At least 3 points are required");
 
 	/* Run core computations: */
Index: /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp	(revision 13101)
@@ -42,5 +42,5 @@
 
 	#ifndef _HAVE_CHACO_ //only works if dakota library has been compiled in.
-	_error2_("Chaco not available! Cannot carry out Chaco partitioning!");
+	_error_("Chaco not available! Cannot carry out Chaco partitioning!");
 	#endif
 
@@ -54,14 +54,14 @@
 	nvtxs = mxGetN(A_IN);
 	mwstart = mxGetJc(A_IN);
-	start=(int*)xmalloc((nvtxs+1)*sizeof(int));
+	start=xNew<int>((nvtxs+1));
 	for (i=0; i<nvtxs+1;i++)start[i]=(int)mwstart[i];
 
 	mwadjacency = mxGetIr(A_IN);
-	adjacency = (int*)xmalloc(mxGetNzmax(A_IN)*sizeof(int));
+	adjacency = xNew<int>(mxGetNzmax(A_IN));
 	for (i=0; i<mxGetNzmax(A_IN); i++) adjacency[i]= (int)mwadjacency[i];
 
 	nedges = start[nvtxs];
 	if(!mxIsEmpty(EWGTS_IN)){
-		ewgts = (float*)xcalloc(nedges, sizeof(float));
+		ewgts = xNewZeroInit<float>(nedges);
 		doublepointer=mxGetPr(A_IN);
 		for (i = 0; i < nedges; i++)ewgts[i] = (float)doublepointer[i];
@@ -77,5 +77,5 @@
 	for (i=0;i<(nterms<10?nterms:10);i++) options[i]=in_options[i]; //copy in_options into default options
 	FetchData(&npart,NPARTS_IN); 
-	nparts=(int*)xmalloc(sizeof(int)); nparts[0]=npart; //weird Chacox interface ain't it?
+	nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
 	FetchData(&goal,&nterms,GOAL_IN); 
 	
@@ -104,5 +104,5 @@
 	
 	/*Allocate output: */
-	assignment = (short*)xcalloc(nvtxs, sizeof(short));
+	assignment = xNewZeroInit<short>(nvtxs);
 	
     /*Call core: */
@@ -110,5 +110,5 @@
 
     /*Output data: */
-	doubleassignment=(double*)xmalloc(nvtxs*sizeof(double));
+	doubleassignment=xNew<double>(nvtxs);
 	for(i=0;i<nvtxs;i++) doubleassignment[i]=(double)assignment[i];
 	WriteData(ASSGN_OUT,doubleassignment,nvtxs);
Index: /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 13101)
@@ -47,5 +47,5 @@
 	if(nlhs!=1 && nlhs!=2){
 		ContourToMeshUsage();
-		_error2_("usage. See above");
+		_error_("usage. See above");
 	}
 	#endif
@@ -53,5 +53,5 @@
 	if(nrhs!=NRHS){
 		ContourToMeshUsage();
-		_error2_("usage. See above");
+		_error_("usage. See above");
 	}
 
@@ -82,5 +82,5 @@
 		WriteData(PLHS1,in_elem);
 	}
-	else _error2_("wrong interpolation type");
+	else _error_("wrong interpolation type");
 
 	/*end module: */
Index: /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 13101)
@@ -68,8 +68,8 @@
 
 	numcontours=mxGetNumberOfElements(matlabstructure);
-	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	contours=xNew<Contour*>(numcontours);
 	for(i=0;i<numcontours;i++){
 		//allocate
-		contouri=(Contour*)xmalloc(sizeof(Contour));
+		contouri=xNew<Contour>(1);
 		//retrieve dimension of this contour.
 		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
Index: /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp	(revision 13101)
@@ -5,13 +5,14 @@
 #include "./EnumToString.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+WRAPPER(EnumToString){
 
 	char    *name    = NULL;
 	int      enum_in;
 
-	/*checks on arguments on the matlab side: */
-	if(nrhs!=NRHS){
-		EnumToStringUsage(); _error2_("usage. See above");
-	}
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&EnumToStringUsage);
 
 	/*Fetch inputs: */
@@ -23,4 +24,7 @@
 	/* output: */
 	WriteData(NAME,name);
+
+	/*end module: */
+	MODULEEND();
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.h	(revision 13101)
@@ -6,7 +6,16 @@
 #define _ENUMTOSTRING_H
 
-/* local prototypes: */
-void EnumToStringUsage(void);
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
+/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -15,9 +24,17 @@
 #include "../../c/issm-binding.h"
     
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define ENUMIN (mxArray*)prhs[0]
-
 /* serial output macros: */
 #define NAME (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define ENUMIN PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define NAME output,0
+#endif
 
 /* serial arg counts: */
@@ -30,3 +47,6 @@
 #define __FUNCT__  "EnumToString"
 
+/* local prototypes: */
+void EnumToStringUsage(void);
+
 #endif  /* _TEST_H */
Index: /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 13101)
@@ -25,8 +25,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
+		Exp2KmlUsage(); _error_("Exp2Kml usage error");
 	}
 	if (nrhs < NRHS) {
-		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
+		Exp2KmlUsage(); _error_("Exp2Kml usage error");
 	}
 
@@ -49,7 +49,7 @@
 
 	/*some checks*/
-	if (sgn !=+1 && sgn !=-1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
-	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
-	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+	if (sgn !=+1 && sgn !=-1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
Index: /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp	(revision 13101)
@@ -26,15 +26,15 @@
 	/*Fetch required fields*/
 	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
-	if(numberofelements<=0) _error2_("No elements found in the model");
+	if(numberofelements<=0) _error_("No elements found in the model");
 	FetchData(&elements,&M,&N,mxGetAssignedField(MODEL,0,"elements"));
-	if(M!=numberofelements || N!=3) _error2_("Field 'elements' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error_("Field 'elements' should be of size [md.numberofelements 3]");
 	FetchData(&elementonwater,&M,&N,mxGetAssignedField(MODEL,0,"elementonwater"));
-	if(M!=numberofelements || N!=1) _error2_("Field 'elementonwater' should be of size [md.numberofelements 1]");
+	if(M!=numberofelements || N!=1) _error_("Field 'elementonwater' should be of size [md.numberofelements 1]");
 	FetchData(&elementconnectivity,&M,&N,mxGetAssignedField(MODEL,0,"elementconnectivity"));
-	if(M!=numberofelements || N!=3) _error2_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
 
 	/*Allocate and initialize all variables*/
 	numberofsegments=0;
-	front=(int*)xmalloc(3*numberofelements*4*sizeof(int));
+	front=xNew<int>(3*numberofelements*4);
 
 	/*Loop over all elements on water*/
@@ -81,5 +81,5 @@
 	/*Now that we know how many segments there is we can allocate the final matrix*/
 	if(numberofsegments){
-		front2=(double*)xmalloc(4*numberofsegments*sizeof(double));
+		front2=xNew<double>(4*numberofsegments);
 		for(i=0;i<4*numberofsegments;i++) front2[i]=(double)front[i];
 	}
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13101)
@@ -46,5 +46,5 @@
 	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=7)){
 		InterpFromGridToMeshUsage();
-		_error2_("usage. See above");
+		_error_("usage. See above");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13101)
@@ -69,9 +69,9 @@
 	if(nlhs!=NLHS){
 		InterpFromMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	if((nrhs!=6) && (nrhs!=7) && (nrhs!=8)){
 		InterpFromMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
@@ -100,8 +100,8 @@
 		/*contours: */
 		numcontours=mxGetNumberOfElements(matlabstructure);
-		contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+		contours=xNew<Contour*>(numcontours);
 		for(i=0;i<numcontours;i++){
 			//allocate
-			contouri=(Contour*)xmalloc(sizeof(Contour));
+			contouri=xNew<Contour>(1);
 			//retrieve dimension of this contour.
 			contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
@@ -131,8 +131,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows){
-		_error2_("vectors x and y should have the same length!");
+		_error_("vectors x and y should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows){
-		_error2_("vectors x_prime and y_prime should have the same length!");
+		_error_("vectors x_prime and y_prime should have the same length!");
 	}
 	
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13101)
@@ -28,5 +28,5 @@
 	if(nlhs!=NLHS){
 		InterpFromMeshToMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	#endif
@@ -34,14 +34,14 @@
 	if(nrhs<NRHS){
 		InterpFromMeshToMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
 	/*Fetch inputs: */
-	FetchData(&index,&nels_data,&test,INDEX); if(test!=3) _error2_("index should have 3 columns");
-	FetchData(&x_data,&nods_data,X);          if(nods_data<3) _error2_("there should be at least three points");
-	FetchData(&y_data,&test,Y);               if(test!=nods_data) _error2_("vectors x and y should have the same length");
-	FetchData(&data,&M_data,&N_data,DATA);    if(M_data*N_data<1) _error2_("data is empty");
-	FetchData(&x_interp,&N_interp,XINTERP);   if(N_interp<1) _error2_("no interpolation requested");
-	FetchData(&y_interp,&test,YINTERP);       if(test!=N_interp) _error2_("vectors x_interp and y_interp should have the same length");
+	FetchData(&index,&nels_data,&test,INDEX); if(test!=3) _error_("index should have 3 columns");
+	FetchData(&x_data,&nods_data,X);          if(nods_data<3) _error_("there should be at least three points");
+	FetchData(&y_data,&test,Y);               if(test!=nods_data) _error_("vectors x and y should have the same length");
+	FetchData(&data,&M_data,&N_data,DATA);    if(M_data*N_data<1) _error_("data is empty");
+	FetchData(&x_interp,&N_interp,XINTERP);   if(N_interp<1) _error_("no interpolation requested");
+	FetchData(&y_interp,&test,YINTERP);       if(test!=N_interp) _error_("vectors x_interp and y_interp should have the same length");
 	FetchData(&options,NRHS,nrhs,ARGUMENTS);
 
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13101)
@@ -76,8 +76,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows || x_data_rows!=z_data_rows){
-		_error2_("vectors x, y and z should have the same length!");
+		_error_("vectors x, y and z should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows || x_prime_rows!=z_prime_rows){
-		_error2_("vectors x_prime, y_prime and z_prime should have the same length!");
+		_error_("vectors x_prime, y_prime and z_prime should have the same length!");
 	}
 	/*get number of elements and number of nodes in the data*/
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 13101)
@@ -45,8 +45,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13101)
@@ -40,8 +40,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
 	}
 
@@ -55,5 +55,5 @@
 			if (notesi && mxIsChar(notesi) && mxGetNumberOfElements(notesi)) {
 				if (!notes) {
-					notes=(char *) xmalloc((mxGetNumberOfElements(notesi)+1)*sizeof(char));
+					notes=xNew<char>(mxGetNumberOfElements(notesi)+1);
 					mxGetString(notesi,notes,mxGetNumberOfElements(notesi)+1);
 				}
@@ -87,15 +87,15 @@
 
 	if (nodecon && (mncon != nnodes))
-	  {_error2_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
+	  {_error_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
 	else if (!nodecon)
 		mncon=nnodes;
 	if ((llat != nnodes) || (llng != nnodes) || (llat != llng))
-		_error2_("Latitude and longitude vectors must be supplied for all nodes.");
+		_error_("Latitude and longitude vectors must be supplied for all nodes.");
 	if (part && (lprt != nnodes))
-		_error2_("Partitioning vector, if supplied, must be supplied for all nodes.");
+		_error_("Partitioning vector, if supplied, must be supplied for all nodes.");
 	if (data && !((mdata == nnodes) || (mdata == melem)))
-		_error2_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
+		_error_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
 	if (cmap && (ncmap != 3))
-		_error2_("Colormap matrix, if supplied, must have three columns for rgb.");
+		_error_("Colormap matrix, if supplied, must have three columns for rgb.");
 	if (!strlen(filnam))
 		strcpy(filnam,"stdout");
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 13101)
@@ -31,8 +31,8 @@
 	/*checks on arguments on the matlab side: */
 	if(nlhs>NLHS){
-		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
 	}
 	if(nrhs<NRHS){
-		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
 	}
 
@@ -51,7 +51,7 @@
 
 	/*some checks*/
-	if (nlat !=2) _error2_("Latitudinal axes \"lataxis\" require two double values, not " << nlat << ".");
-	if (nlong!=2) _error2_("Longitudinal axes \"longaxis\" require two double values, not " << nlong << ".");
-	if (!nimages) _error2_("No image files provided.");
+	if (nlat !=2) _error_("Latitudinal axes \"lataxis\" require two double values, not " << nlat << ".");
+	if (nlong!=2) _error_("Longitudinal axes \"longaxis\" require two double values, not " << nlong << ".");
+	if (!nimages) _error_("No image files provided.");
 
 	if ((int)dzip){
@@ -90,5 +90,5 @@
 		if (verbose) _printLine_(czip);
 
-		if (mexEvalString(czip)) _error2_("Error zipping file \"" << filkmz << "\".");
+		if (mexEvalString(czip)) _error_("Error zipping file \"" << filkmz << "\".");
 		xfree((void**)&czip);
 		xfree((void**)&filkmz);
Index: /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 13101)
@@ -22,8 +22,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
+		Kml2ExpUsage(); _error_("Kml2Exp usage error");
 	}
 	if (nrhs < NRHS) {
-		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
+		Kml2ExpUsage(); _error_("Kml2Exp usage error");
 	}
 
@@ -43,7 +43,7 @@
 
 	/*some checks*/
-	if (sgn !=+1 && sgn!= -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
-	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
-	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+	if (sgn !=+1 && sgn!= -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
Index: /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp	(revision 13101)
@@ -22,13 +22,13 @@
 	/*checks on arguments on the matlab side: */
 	if (nrhs<NRHS || nlhs>NLHS){
-		KrigingUsage(); _error2_("Kriging usage error");
+		KrigingUsage(); _error_("Kriging usage error");
 	}
 
 	/*Fetch inputs: */
 	FetchData(&x,&n_obs,X);
-	FetchData(&y,&N,Y);                       if(n_obs!=N) _error2_("x and y should have the same size");
-	FetchData(&observations,&N,OBSERVATIONS); if(n_obs!=N) _error2_("x and observations should have the same size");
+	FetchData(&y,&N,Y);                       if(n_obs!=N) _error_("x and y should have the same size");
+	FetchData(&observations,&N,OBSERVATIONS); if(n_obs!=N) _error_("x and observations should have the same size");
 	FetchData(&x_interp,&M_interp,&N_interp,XINTERP);
-	FetchData(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error2_("x_interp and y_interp should have the same size");
+	FetchData(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error_("x_interp and y_interp should have the same size");
 	FetchData(&options,NRHS,nrhs,prhs);
 
Index: /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp	(revision 13101)
@@ -25,8 +25,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Ll2xyUsage(); _error2_("Ll2xy usage error");
+		Ll2xyUsage(); _error_("Ll2xy usage error");
 	}
 	if (nrhs < NRHS) {
-		Ll2xyUsage(); _error2_("Ll2xy usage error");
+		Ll2xyUsage(); _error_("Ll2xy usage error");
 	}
 
@@ -47,9 +47,9 @@
 	/*some checks*/
 	if (verbose) _printLine_("Checking inputs:");
-	if (nlat != nlon){_error2_("Must have same number of lat[" << nlat << "] and lon[" << nlon << "] coordinates.");}
+	if (nlat != nlon){_error_("Must have same number of lat[" << nlat << "] and lon[" << nlon << "] coordinates.");}
 	else                ncoord=nlat;
-	if (sgn != +1 && sgn != -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
-	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
-	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	x=(double*)mxMalloc(ncoord*sizeof(double));
Index: /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp	(revision 13101)
@@ -74,10 +74,10 @@
 
 	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
-	element_partitioning=(double*)xmalloc(numberofelements*sizeof(double));
+	element_partitioning=xNew<double>(numberofelements);
 	for (i=0;i<numberofelements;i++){
 		element_partitioning[i]=(double)int_element_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
 	}
 	
-	node_partitioning=(double*)xmalloc(numberofvertices*sizeof(double));
+	node_partitioning=xNew<double>(numberofvertices);
 	for (i=0;i<numberofvertices;i++){
 		node_partitioning[i]=(double)int_node_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
Index: /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13101)
@@ -54,6 +54,6 @@
 	//index
 	FetchData(&double_index,&nel,&dummy,INDEX);
-	if(dummy!=3 && dummy!=6)_error2_("element triangulation should be of 3 or 6 column width!");
-	index=(int*)xmalloc(nel*3*sizeof(int));
+	if(dummy!=3 && dummy!=6)_error_("element triangulation should be of 3 or 6 column width!");
+	index=xNew<int>(nel*3);
 	for(i=0;i<nel;i++){
 		for(j=0;j<3;j++){
@@ -67,8 +67,8 @@
 	//contours
 	numcontours=mxGetNumberOfElements(matlabstructure);
-	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	contours=xNew<Contour*>(numcontours);
 	for(i=0;i<numcontours;i++){
 		//allocate
-		contouri=(Contour*)xmalloc(sizeof(Contour));
+		contouri=xNew<Contour>(1);
 		//retrieve dimension of this contour.
 		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
Index: /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp	(revision 13101)
@@ -25,5 +25,5 @@
 
 #ifndef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
-	_error2_("Scotch not available! Cannot carry out Scotch partitioning!");
+	_error_("Scotch not available! Cannot carry out Scotch partitioning!");
 	#else
 
Index: /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 13101)
@@ -25,5 +25,5 @@
 
 	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
-	_error2_("Shapelib not available! Cannot carry out shp file translation!");
+	_error_("Shapelib not available! Cannot carry out shp file translation!");
 	#endif
 
@@ -33,8 +33,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
+		Shp2KmlUsage(); _error_("Shp2Kml usage error");
 	}
 	if (nrhs < NRHS) {
-		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
+		Shp2KmlUsage(); _error_("Shp2Kml usage error");
 	}
 
@@ -54,7 +54,7 @@
 
 	/*some checks*/
-	if (sgn < -1 || sgn > +1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north), -1 (south), or 0 (no translation).");
-	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
-	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+	if (sgn < -1 || sgn > +1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north), -1 (south), or 0 (no translation).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
Index: /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp	(revision 13101)
@@ -5,13 +5,14 @@
 #include "./StringToEnum.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+WRAPPER(StringToEnum){
 
 	char    *name    = NULL;
 	int      enum_out;
 
-	/*checks on arguments on the matlab side: */
-	if(nrhs!=NRHS){
-		StringToEnumUsage(); _error2_("usage. See above");
-	}
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&StringToEnumUsage);
 
 	/*Fetch inputs: */
@@ -23,4 +24,7 @@
 	/* output: */
 	WriteData(ENUMOUT,enum_out);
+
+	/*end module: */
+	MODULEEND();
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.h	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.h	(revision 13101)
@@ -6,7 +6,16 @@
 #define _STRINGTOENUM_H
 
-/* local prototypes: */
-void StringToEnumUsage(void);
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
+/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -15,9 +24,17 @@
 #include "../../c/issm-binding.h"
     
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define NAME (mxArray*)prhs[0]
-
 /* serial output macros: */
 #define ENUMOUT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define NAME PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define ENUMOUT output,0
+#endif
 
 /* serial arg counts: */
@@ -30,3 +47,6 @@
 #define __FUNCT__  "StringToEnum"
 
+/* local prototypes: */
+void StringToEnumUsage(void);
+
 #endif  /* _TEST_H */
Index: /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13101)
@@ -73,5 +73,5 @@
 		nel=mxGetM(prhs[0]);
 		tindex_in=mxGetPr(prhs[0]);
-		index_in=(double*)xmalloc(nel*3*sizeof(double));
+		index_in=xNew<double>(nel*3);
 		for (i=0;i<nel;i++){
 			for (j=0;j<3;j++){
@@ -88,5 +88,5 @@
 		nods=mxGetM(prhs[1]);
 		x_inm=mxGetPr(prhs[1]);
-		x_in=(double*)xmalloc(nods*sizeof(double));
+		x_in=xNew<double>(nods);
 		for (i=0;i<nods;i++){
 			x_in[i]=x_inm[i];
@@ -100,5 +100,5 @@
 	if(mxIsDouble(prhs[2])){
 		y_inm=mxGetPr(prhs[2]);
-		y_in=(double*)xmalloc(nods*sizeof(double));
+		y_in=xNew<double>(nods);
 		for (i=0;i<nods;i++){
 			y_in[i]=y_inm[i];
@@ -113,5 +113,5 @@
 		num_seg=mxGetM(prhs[3]);
 		tsegments_in=mxGetPr(prhs[3]);
-		segments_in=(double*)xmalloc(num_seg*3*sizeof(double));
+		segments_in=xNew<double>(num_seg*3);
 		for (i=0;i<num_seg;i++){
 			for (j=0;j<3;j++){
@@ -127,5 +127,5 @@
 	if(mxIsDouble(prhs[4])){
 		tsegmentmarkers_in=mxGetPr(prhs[4]);
-		segmentmarkers_in=(double*)xmalloc(num_seg*sizeof(double));
+		segmentmarkers_in=xNew<double>(num_seg);
 		for (i=0;i<num_seg;i++){
 			segmentmarkers_in[i]=tsegmentmarkers_in[i];
Index: /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp	(revision 13101)
@@ -24,8 +24,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Xy2llUsage(); _error2_("Xy2ll usage error");
+		Xy2llUsage(); _error_("Xy2ll usage error");
 	}
 	if (nrhs < NRHS) {
-		Xy2llUsage(); _error2_("Xy2ll usage error");
+		Xy2llUsage(); _error_("Xy2ll usage error");
 	}
 
@@ -45,9 +45,9 @@
 
 	/*some checks*/
-	if   (nx != ny){_error2_("Must have same number of x[" << nx << "] and y[" << ny << "] coordinates.");}
+	if   (nx != ny){_error_("Must have same number of x[" << nx << "] and y[" << ny << "] coordinates.");}
 	else            ncoord=nx;
-	if (sgn != +1 && sgn != -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
-	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
-	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	lat=(double*)mxMalloc(ncoord*sizeof(double));
Index: /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am	(revision 13101)
@@ -1,45 +1,55 @@
-INCLUDES = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+
 EXEEXT=$(MATLABWRAPPEREXT)
-#Bin programs {{{1
+
+#Modules {{{1
 if MODULES
-bin_PROGRAMS =  AverageFilter\
-				BamgMesher\
-				BamgConvertMesh\
-				BamgTriangulate\
-				Chaco\
-				ContourToMesh \
-				ContourToNodes \
-				ElementConnectivity\
-				EnumToString\
-				Exp2Kml \
-				HoleFiller \
-				InternalFront\
-				InterpFromGridToMesh \
-				InterpFromMeshToMesh2d \
-				InterpFromMeshToMesh3d \
-				InterpFromMeshToGrid \
-				InterpFromMesh2d \
-				KMLFileRead \
-				KMLMeshWrite \
-				KMLOverlay \
-				Kml2Exp \
-				Kriging \
-				Ll2xy \
-				NodeConnectivity \
-				MeshPartition\
-				MeshProfileIntersection\
-				PointCloudFindNeighbors\
-				PropagateFlagsFromConnectivity\
-				Scotch\
-				Shp2Kml\
-				StringToEnum\
-				TriaSearch\
-				TriMesh\
-				TriMeshProcessRifts\
-				Xy2ll
+lib_LTLIBRARIES =  AverageFilter.la\
+			       BamgMesher.la\
+				   BamgConvertMesh.la\
+				   BamgTriangulate.la\
+				   ContourToMesh.la\
+				   ContourToNodes.la\
+				   ElementConnectivity.la\
+				   EnumToString.la\
+				   Exp2Kml.la\
+				   HoleFiller.la\
+				   InternalFront.la\
+				   InterpFromGridToMesh.la\
+				   InterpFromMeshToMesh2d.la\
+				   InterpFromMeshToMesh3d.la\
+				   InterpFromMeshToGrid.la\
+				   InterpFromMesh2d.la\
+				   KMLFileRead.la\
+				   KMLMeshWrite.la\
+				   KMLOverlay.la\
+				   Kml2Exp.la\
+				   Kriging.la\
+				   Ll2xy.la\
+				   NodeConnectivity.la\
+				   MeshPartition.la\
+				   MeshProfileIntersection.la\
+				   PointCloudFindNeighbors.la\
+				   PropagateFlagsFromConnectivity.la\
+				   Shp2Kml.la\
+				   StringToEnum.la\
+				   TriaSearch.la\
+				   TriMesh.la\
+				   TriMeshProcessRifts.la\
+				   Scotch.la\
+				   Xy2ll.la\
+                   Chaco.la
 endif 
 #}}}
 #Flags and libraries {{{1
-LDADD = ../../c/libISSMCore.a ../../c/libISSMModules.a $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
+if SHAREDLIBS
+deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
+else
+deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+endif
+
+deps +=  $(MATHLIB) ${MEXLIB}
+
+#$(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB) 
 
 #Triangle library
@@ -47,120 +57,176 @@
 
 #Matlab part
-AM_LDFLAGS   = $(MEXLINK)
+AM_LDFLAGS = $(MEXLINK) -shrext ${EXEEXT} -module
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+if SHAREDLIBS
+deps += ../../c/libISSMMatlab.la 
+else
+deps += ../../c/libISSMMatlab.a
+AM_LDFLAGS += --no-warnings 
+endif
+
 AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_ -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
-LDADD       += $(MEXLIB) ../../c/libISSMMatlab.a 
-LDADD       += ../../c/libISSMCore.a 
-if CIRCULAR_DEPENDENCIES
-LDADD       += $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
-endif
-LDADD       += ../../c/libISSMModules.a
+
+######################################################################################
+# Circular dependencies may not be necessary here.
+#deps += ../../c/libISSMCore.a 
+#if CIRCULAR_DEPENDENCIES
+#deps += $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
+#endif
+######################################################################################
+
+if SHAREDLIBS
+deps +=
+else
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a
+endif
 
 #Optimization flags:
 AM_CXXFLAGS += $(CXXOPTFLAGS) 
 #}}}
+
 #Bin sources {{{1
-AverageFilter_SOURCES = ../AverageFilter/AverageFilter.cpp\
+AverageFilter_la_SOURCES = ../AverageFilter/AverageFilter.cpp\
 			  ../AverageFilter/AverageFilter.h
-
-BamgMesher_SOURCES = ../BamgMesher/BamgMesher.cpp\
+AverageFilter_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
 					../BamgMesher/BamgMesher.h
-
-BamgConvertMesh_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
 					../BamgConvertMesh/BamgConvertMesh.h
-
-BamgTriangulate_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
 								  ../BamgTriangulate/BamgTriangulate.h
-
-Chaco_SOURCES = ../Chaco/Chaco.cpp\
+BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
 					../Chaco/Chaco.h
-
-ContourToMesh_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
-			  ../ContourToMesh/ContourToMesh.h
-
-ContourToNodes_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+			               ../ContourToMesh/ContourToMesh.h
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
 			  ../ContourToNodes/ContourToNodes.h
-
-ElementConnectivity_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
 			  ../ElementConnectivity/ElementConnectivity.h
-
-EnumToString_SOURCES = ../EnumToString/EnumToString.cpp\
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
 			  ../EnumToString/EnumToString.h
-
-StringToEnum_SOURCES = ../StringToEnum/StringToEnum.cpp\
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
 			  ../StringToEnum/StringToEnum.h
-
-HoleFiller_SOURCES = ../HoleFiller/HoleFiller.cpp\
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+HoleFiller_la_SOURCES = ../HoleFiller/HoleFiller.cpp\
 			  ../HoleFiller/HoleFiller.h
-
-InternalFront_SOURCES = ../InternalFront/InternalFront.cpp\
+HoleFiller_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) 
+
+InternalFront_la_SOURCES = ../InternalFront/InternalFront.cpp\
 										 ../InternalFront/InternalFront.h
-
-InterpFromGridToMesh_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+InternalFront_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
 			  ../InterpFromGridToMesh/InterpFromGridToMesh.h
-
-InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
 							../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-
-InterpFromMeshToMesh3d_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
 									../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
-
-InterpFromMeshToGrid_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
 									../InterpFromMeshToGrid/InterpFromMeshToGrid.h
-
-InterpFromMesh2d_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
 									../InterpFromMesh2d/InterpFromMesh2d.h
-
-KMLFileRead_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
+InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
 			  ../KMLFileRead/KMLFileRead.h
-
-KMLMeshWrite_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
+KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
 			  ../KMLMeshWrite/KMLMeshWrite.h
-
-KMLOverlay_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
+KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
 			  ../KMLOverlay/KMLOverlay.h
-
-Xy2ll_SOURCES = ../Xy2ll/Xy2ll.cpp\
+KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp\
 			  ../Xy2ll/Xy2ll.h
-
-Ll2xy_SOURCES = ../Ll2xy/Ll2xy.cpp\
+Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp\
 			  ../Ll2xy/Ll2xy.h
-
-Exp2Kml_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
+Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
 			  ../Exp2Kml/Exp2Kml.h
-
-Kml2Exp_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
+Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
 			  ../Kml2Exp/Kml2Exp.h
-
-Kriging_SOURCES = ../Kriging/Kriging.cpp\
+Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Kriging_la_SOURCES = ../Kriging/Kriging.cpp\
 						../Kriging/Kriging.h
-
-MeshPartition_SOURCES = ../MeshPartition/MeshPartition.cpp\
+Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp\
 			  ../MeshPartition/MeshPartition.h
-
-MeshProfileIntersection_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
 			  ../MeshProfileIntersection/MeshProfileIntersection.h
-
-NodeConnectivity_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
 										../NodeConnectivity/NodeConnectivity.h
-
-PointCloudFindNeighbors_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
 			  ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
-
-PropagateFlagsFromConnectivity_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
 			  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
-
-Scotch_SOURCES = ../Scotch/Scotch.cpp\
-			  ../Scotch/Scotch.h
-
-Shp2Kml_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
-			  ../Shp2Kml/Shp2Kml.h
-
-TriaSearch_SOURCES = ../TriaSearch/TriaSearch.cpp\
+PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Scotch_la_SOURCES = ../Scotch/Scotch.cpp\
+                    ../Scotch/Scotch.h
+Scotch_la_LIBADD = ${deps} $(SCOTCHLIB)
+
+Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
+                     ../Shp2Kml/Shp2Kml.h
+Shp2Kml_la_LIBADD = ${deps}
+
+TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp\
 			  ../TriaSearch/TriaSearch.h
-
-TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
-			  ../TriMesh/TriMesh.h
-
-TriMeshProcessRifts_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
+                     ../TriMesh/TriMesh.h
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
 			  ../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 #}}}
Index: /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am	(revision 13101)
@@ -1,10 +1,12 @@
-INCLUDES = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
 EXEEXT=$(PYTHONWRAPPEREXT)
 #Bin programs {{{1
 if MODULES
 bin_PROGRAMS = ElementConnectivity\
+			   EnumToString\
 			   InterpFromMeshToMesh2d \
 			   NodeConnectivity\
-			   TriMesh 
+			   StringToEnum\
+			   TriMesh
 endif 
 #}}}
@@ -32,4 +34,7 @@
 			  ../ElementConnectivity/ElementConnectivity.h
 
+EnumToString_SOURCES = ../EnumToString/EnumToString.cpp\
+			  ../EnumToString/EnumToString.h
+
 InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
 							../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
@@ -38,4 +43,7 @@
 										../NodeConnectivity/NodeConnectivity.h
 
+StringToEnum_SOURCES = ../StringToEnum/StringToEnum.cpp\
+			  ../StringToEnum/StringToEnum.h
+
 TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
 			  ../TriMesh/TriMesh.h
Index: sm/branches/trunk-jpl-damage/src/py/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/py/Makefile.am	(revision 13100)
+++ 	(revision )
@@ -1,1 +1,0 @@
-SUBDIRS = model
Index: /issm/branches/trunk-jpl-damage/startup.m
===================================================================
--- /issm/branches/trunk-jpl-damage/startup.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/startup.m	(revision 13101)
@@ -27,6 +27,7 @@
 
 %ISSM path
-addpath([ISSM_DIR '/src/m/utils/']); %loads recursivepath
+addpath([ISSM_DIR '/src/m/os/']); %loads recursivepath
 addpath([ISSM_DIR '/bin']);
+addpath([ISSM_DIR '/lib']);
 addpath(recursivepath([ISSM_DIR '/src/m']));
 addpath(recursivepath([ISSM_DIR '/externalpackages/scotch']));
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py	(revision 13101)
@@ -67,6 +67,6 @@
 		234 : 'SquareShelfTranForceNeg2dDakotaSamp',
 		235 : 'SquareShelfTranForceNeg2dDakotaLocal',
-		236 : 'SquareShelfTranIspddIsdeltaM2d';
-		237 : 'SquareShelfTranIspddIsdeltaM3d';
+		236 : 'SquareShelfTranIspddIsdeltaM2d',
+		237 : 'SquareShelfTranIspddIsdeltaM3d',
 		301 : 'SquareSheetConstrainedDiagM2d',
 		302 : 'SquareSheetConstrainedDiagH2d',
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 13101)
@@ -72,11 +72,11 @@
 % }}}
 %GET ids  {{{1
-list=dir;%use dir, as it seems to act OS independent
+flist=dir;%use dir, as it seems to act OS independent
 list_ids=[];
-for i=1:numel(list),
-	if ( strncmp(list(i).name,'test',4) &...                         %File name must start with 'test'
-			strncmp(fliplr(list(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
-			~strcmp(list(i).name,'test.m'))                            %File name must be different than 'test.m'
-		list_ids(end+1)=eval(list(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
+for i=1:numel(flist),
+	if ( strncmp(flist(i).name,'test',4) &...                         %File name must start with 'test'
+			strncmp(fliplr(flist(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
+			~strcmp(flist(i).name,'test.m'))                            %File name must be different than 'test.m'
+		list_ids(end+1)=eval(flist(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
 	end
 end
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py	(revision 13101)
@@ -42,4 +42,5 @@
 	from parallelrange import parallelrange
 	from IdToName import IdToName
+	from MatlabFuncs import *
 
 	#Get ISSM_DIR variable
@@ -49,15 +50,15 @@
 	#Process options
 	#GET benchmark {{{1
-	if not benchmark.lower() in ['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing']:
+	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing']):
 		print "runme warning: benchmark '%s' not supported, defaulting to test 'nightly'." % benchmark
 		benchmark='nightly'
 	# }}}
 	#GET procedure {{{1
-	if not procedure.lower() in ['check','update']:
+	if not ismember(procedure,['check','update']):
 		print "runme warning: procedure '%s' not supported, defaulting to test 'check'." % procedure
 		procedure='check'
 	# }}}
 	#GET output {{{1
-	if not output.lower() in ['nightly','daily','none']:
+	if not ismember(output,['nightly','daily','none']):
 		print "runme warning: output '%s' not supported, defaulting to test 'none'." % output
 		output='none'
@@ -107,17 +108,17 @@
 
 	#Process Ids according to benchmarks {{{1
-	if   benchmark.lower() == 'nightly':
+	if   strcmpi(benchmark,'nightly'):
 		test_ids=test_ids.intersection(set(range(1,1000)))
-	elif benchmark.lower() == 'ismip':
+	elif strcmpi(benchmark,'ismip'):
 		test_ids=test_ids.intersection(set(range(1101,1200)))
-	elif benchmark.lower() == 'eismint':
+	elif strcmpi(benchmark,'eismint'):
 		test_ids=test_ids.intersection(set(range(1201,1300)))
-	elif benchmark.lower() == 'thermal':
+	elif strcmpi(benchmark,'thermal'):
 		test_ids=test_ids.intersection(set(range(1301,1400)))
-	elif benchmark.lower() == 'mesh':
+	elif strcmpi(benchmark,'mesh'):
 		test_ids=test_ids.intersection(set(range(1401,1500)))
-	elif benchmark.lower() == 'validation':
+	elif strcmpi(benchmark,'validation'):
 		test_ids=test_ids.intersection(set(range(1001,2000)))
-	elif benchmark.lower() == 'tranforcing':
+	elif strcmpi(benchmark,'tranforcing'):
 		test_ids=test_ids.intersection(set(range(1501,1503)))
 #	print 'test_ids after benchmark =',test_ids
@@ -139,7 +140,7 @@
 			#UPDATE ARCHIVE?
 			archive_name='Archive'+str(id)
-			if procedure.lower() == 'update':
-
-				if not socket.gethostname().lower().split('.')[0] == 'larsen':
+			if strcmpi(procedure,'update'):
+
+				if not strcmp(socket.gethostname().lower().split('.')[0],'larsen'):
 #					raise RuntimeError("Nightly run archives must be saved on 'larsen' (hostname is '"+socket.gethostname()+"').")
 					print "Nightly run archives must be saved on 'larsen' (hostname is '"+socket.gethostname()+"')."
@@ -200,5 +201,5 @@
 						directory=os.getcwd().split('/')    #  not used?
 						message=me2
-						if   output.lower() == 'nightly':
+						if   strcmpi(output,'nightly'):
 							fid=open(os.path.join(ISSM_DIR,'nightlylog','matlaberror.log'), 'a')
 							fid.write('%s' % message)
@@ -206,5 +207,5 @@
 							fid.close()
 							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
-						elif output.lower() == 'daily':
+						elif strcmpi(output,'daily'):
 							fid=open(os.path.join(ISSM_DIR,'dailylog','matlaberror.log'), 'a')
 							fid.write('%s' % message)
@@ -223,5 +224,5 @@
 			directory=os.getcwd().split('/')    #  not used?
 			message=me
-			if   output.lower() == 'nightly':
+			if   strcmpi(output,'nightly'):
 				fid=open(os.path.join(ISSM_DIR+'nightlylog','matlaberror.log'), 'a')
 				fid.write('%s' % message)
@@ -229,5 +230,5 @@
 				fid.close()
 				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
-			elif output.lower() == 'daily':
+			elif strcmpi(output,'daily'):
 				fid=open(os.path.join(ISSM_DIR+'dailylog','matlaberror.log'), 'a')
 				fid.write('%s' % message)
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.py	(revision 13101)
@@ -14,6 +14,6 @@
 md=setflowequation(md,'macayeal','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.diagnostic.requested_outputs=StressTensorEnum
-md=solve(md,DiagnosticSolutionEnum)
+md.diagnostic.requested_outputs=StressTensorEnum()
+md=solve(md,DiagnosticSolutionEnum())
 
 #Fields and tolerances to track changes
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 13101)
@@ -84,5 +84,5 @@
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
 field_names     ={'importancefactors'};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 13101)
@@ -2,7 +2,7 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
 md=extrude(md,3,1);
 md=setflowequation(md,'pattyn','all');
-md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
 md.cluster=generic('name',oshostname(),'np',3);
 md.prognostic.hydrostatic_adjustment='Incremental';
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 13101)
@@ -56,5 +56,5 @@
 %solve
 md=solve(md,TransientSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 
 %Fields and tolerances to track changes
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 13101)
@@ -56,5 +56,5 @@
 %solve
 md=solve(md,TransientSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 
 %Fields and tolerances to track changes
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 13101)
@@ -36,5 +36,5 @@
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
 field_names     ={'importancefactors'};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 13101)
@@ -37,5 +37,5 @@
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
 field_names     ={'importancefactors'};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 13101)
@@ -49,5 +49,5 @@
 %solve
 md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 
 %Fields and tolerances to track changes
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 13101)
@@ -53,5 +53,5 @@
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 
 %ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 13101)
@@ -33,5 +33,5 @@
 %solve
 md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
+md.qmu.results=md.results.dakota;
 
 %test on thickness
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 13101)
@@ -8,5 +8,5 @@
 md=extrude(md,3,1);
 md=setflowequation(md,'stokes','all');
-md=modelextract(md,md.mask.elementonfloatingice);
+md=extract(md,md.mask.elementonfloatingice);
 
 %control parameters
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 13101)
@@ -6,5 +6,5 @@
 
 %Ice sheet only
-md=modelextract(md,md.mask.elementongroundedice);
+md=extract(md,md.mask.elementongroundedice);
 pos=find(md.mesh.vertexonboundary);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
Index: /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py	(revision 13100)
+++ /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py	(revision 13101)
@@ -2,8 +2,9 @@
 from verbose import *
 import scipy.io as matio
-import InterpFromMeshToMesh2d as im
-from   paterson import  *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import  *
 from SetIceShelfBC import *
 import inspect
+import os.path
 
 #Start defining model parameters here
@@ -29,6 +30,6 @@
 index=reshape(index.T,(len(index),3),order='F')
 
-md.initialization.vx = im.InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)
-md.initialization.vy = im.InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)
+[md.initialization.vx] = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)
+[md.initialization.vy] = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)
 md.initialization.vz = zeros(md.mesh.numberofvertices)
 md.initialization.pressure = zeros(md.mesh.numberofvertices)
@@ -62,4 +63,4 @@
 #Change name so that no tests have the same name
 if len(inspect.stack()) > 2:
-    md.miscellaneous.name = inspect.stack()[2][1].split('.')[0]
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
 
